Can't access model attribute from other model in Django - django-models

I need to access an attribute from a related model (to use as a filter attribute in an admin), but I get this error: 'EventTimeAdmin.list_filter[1]' refers to field 'event__sites' that is missing from model 'EventTime'.
Here is are the relevant classes from models.py:
class Event(models.Model):
title = models.CharField(max_length=100)
short_description = models.CharField(max_length=250, blank=True)
long_description = models.TextField(blank=True)
place = models.ForeignKey(Place, related_name="events", default=0, blank=True, null=True)
one_off_place = models.CharField('one-off place', max_length=100, blank=True)
phone = models.CharField(max_length=40)
cost_low = models.DecimalField('cost (low)', max_digits=7, decimal_places=2, blank=True, null=True)
cost_high = models.DecimalField('cost (high)', max_digits=7, decimal_places=2, blank=True, null=True)
age_lowest = models.PositiveSmallIntegerField('lowest age', blank=True, null=True, help_text='Use 0 for "all ages". Leave blank if no age information is available') # Not every event submits info about age limits
priority = models.ForeignKey(EventPriority)
ticket_website = models.URLField('ticket Web site', blank=True)
posted_date = models.DateTimeField('date entered', default=datetime.datetime.now())
updated_date = models.DateTimeField('date updated', editable=False, blank=True)
small_photo = models.ImageField(upload_to='img/events/%Y', blank=True)
teaser_text = models.TextField(max_length=1000, blank=True)
is_ongoing_indefinitely = models.BooleanField(db_index=True, help_text="If this box is checked, the event won't be displayed by default in the event search. Users will have to manually select \"Display ongoing events\" in order to display it.")
is_national_act = models.BooleanField('is a national marquee touring act')
categories = models.ManyToManyField(EventCategory, related_name="events")
bands = models.ManyToManyField(Band, related_name="events", blank=True)
sites = models.ManyToManyField(Site)
related_links = generic.GenericRelation(RelatedLink)
generic_galleries = generic.GenericRelation(GalleryRelationsPiece)
staff_photographer_attending = models.BooleanField('Staff Photographer will be attending')
index = EventIndex()
class Meta:
ordering = ('title',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.updated_date = datetime.datetime.now()
super(Event, self).save(*args, **kwargs)
def get_absolute_url(self):
if self.is_recurring():
return reverse('ellington_events_ongoing_detail', args=[self.id])
else:
next = self.get_next_time()
if next:
return next.get_absolute_url()
else:
try:
last = self.event_times.order_by("-event_date", "start_time")[0]
return last.get_absolute_url()
except IndexError:
return reverse('ellington_events_todays_events', args=[])
#property
def _sites(self):
"""A property used for indexing which sites this object belongs to."""
return [s.id for s in self.sites.all()]
# def start_time(self):
# return self.event_times.start_time
# TODO: Redundant
def get_absolute_url_recurring(self):
"Returns the absolute URL for this event's recurring-event page"
return reverse('ellington_events_ongoing_detail', args=[self.id])
def is_recurring(self):
"""Returns ``True`` if this event is a recurring event."""
return bool(self.recurring_event_times.count())
def get_cost(self):
"Returns this event's cost as a pretty formatted string such as '$3 - $5'"
if self.cost_low == self.cost_high == 0:
return 'Free'
if self.cost_low == self.cost_high == None:
return ''
if self.cost_low == 0 and self.cost_high == None:
return 'Free'
elif self.cost_low == None and self.cost_high == 0:
return 'Free'
if self.cost_low == self.cost_high:
cost = '$%.2f' % self.cost_low
elif self.cost_low == 0 or self.cost_low == None:
cost = 'Free - $%.2f' % self.cost_high
elif self.cost_high == 0 or self.cost_high == None:
cost = '$%.2f' % self.cost_low
else:
cost = '$%.2f - $%.2f' % (self.cost_low, self.cost_high)
return cost.replace('.00', '')
def get_age_limit(self):
"Returns this event's age limit as a pretty formatted string such as '21+'"
if self.age_lowest is None:
return 'Not available'
if self.age_lowest == 0:
return 'All ages'
return '%s+' % self.age_lowest
def get_place_name(self):
"Returns this event's venue, taking into account the one_off_place field."
if self.one_off_place:
return self.one_off_place
if self.place is not None:
return self.place.name
else:
return ""
def get_next_time(self):
"""
Return the next (in the future) ``EventTime`` for this ``Event``.
Assumes the event is not recurring. Returns ``None`` if no next time is
available.
"""
now = datetime.datetime.now()
for et in self.event_times.filter(event_date__gte=now.date()).order_by("event_date", "start_time"):
try:
dt = datetime.datetime.combine(et.event_date, et.start_time)
except TypeError:
return None
if dt >= now:
return et
return None
# TODO: proprietary
def get_lj_category(self):
"""
Returns either 'Nightlife', 'Music', 'Theater', 'Misc.' or
'Museums and Galleries' for this event.
"""
MAPPING = (
('Activities', 'Misc.'),
('Art', 'Museums and Galleries'),
('Children', 'Misc.'),
('Community', 'Misc.'),
('Culinary', 'Misc.'),
('KU calendar', 'Misc.'),
('Lectures', 'Misc.'),
('Museums', 'Museums and Galleries'),
('Performance', 'Misc.'),
)
# "Performance | Theater" is a special case.
for c in self.categories.all():
if str(c) == "Performance | Theater":
return 'Theater'
parent_categories = [c.parent_category for c in self.categories.all()]
for parent_category, lj_category in MAPPING:
if parent_category in parent_categories:
return lj_category
# Failing that, we must be in either 'Music', which can be either
# 'Music' or 'Nightlife', depending on the venue.
if self.one_off_place:
return 'Music'
# If it's downtown, it's 'Nightlife'. Otherwise, it's 'Music'.
if "downtown" in self.place.neighborhood.lower():
return 'Nightlife'
return 'Music'
class EventTime(models.Model):
event = models.ForeignKey(Event, related_name="event_times")
event_date = models.DateField('date')
start_time = models.TimeField(blank=True, null=True)
finish_time = models.TimeField(blank=True, null=True)
objects = EventTimeManager()
def long_desc(self):
return self.event.long_description
# def sites(self):
# return self.event._sites
# def sites(self):
# return self.event.sites
# #property
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in self.event.sites.all()]
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in self.event.sites.all()]
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in event.sites.all()]
class Meta:
ordering = ('event_date', 'start_time')
def __unicode__(self):
return u"%s -- %s at %s" % (self.event.title, self.event_date.strftime("%m/%d/%y"), self.event.get_place_name())
def get_absolute_url(self):
year = self.event_date.strftime("%Y")
month = self.event_date.strftime("%b").lower()
day = self.event_date.strftime("%d")
return reverse('ellington_events_event_detail', args=[year, month, day, self.event.id])
def get_time(self):
"Returns this event's time as a pretty formatted string such as '3 p.m. to 5 p.m.'"
if self.start_time is not None and self.finish_time is not None:
return '%s to %s' % (dateformat.time_format(self.start_time, 'P'), dateformat.time_format(self.finish_time, 'P'))
elif self.start_time is not None:
return dateformat.time_format(self.start_time, 'P')
return 'time TBA'
def get_part_of_day(self):
"""
Returns a string describing the part of day this event time is taking
place -- either 'Morning', 'Afternoon', 'Evening' or 'Night'.
"""
if self.start_time is None:
return 'Time not available'
if 3 < self.start_time.hour < 12:
return 'Morning'
elif 12 <= self.start_time.hour < 18:
return 'Afternoon'
elif 18 <= self.start_time.hour < 21:
return 'Evening'
return 'Night'
def is_in_the_past(self):
return self.event_date < datetime.date.today()
def happens_this_year(self):
return datetime.date.today().year == self.event_date.year
def get_other_event_times(self):
"Returns a list of all other EventTimes for this EventTime's Event"
if not hasattr(self, "_other_event_times_cache"):
self._other_event_times_cache = [et for et in self.event.event_times.order_by("event_date", "start_time") if et.id != self.id]
return self._other_event_times_cache
# TODO: proprietary
def get_weather_forecast(self):
"Returns a weather.forecast.DayForecast object for this EventTime"
try:
from ellington.weather.models import DayForecast
except ImportError:
return None
if not self.event.place.is_outdoors:
raise DayForecast.DoesNotExist
if not hasattr(self, "_weather_forecast_cache"):
self._weather_forecast_cache = DayForecast.objects.get(full_date=self.event_date)
return self._weather_forecast_cache
DAY_OF_WEEK_CHOICES = (
(0, 'Sunday'),
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
(6, 'Saturday'),
)
The thing is, event__title is accessed from EventTimeAdmin:
class EventTimeAdmin(admin.ModelAdmin):
list_display = ('event', 'event_date', 'start_time', 'finish_time','long_desc')
list_filter = ('event_date','event__sites')
search_fields = ('event__title', 'event_date')
ordering = ('-event_date',)
class Meta:
model = EventTime
But event__sites is not accessible... why is that?
Edit: You can see my attempts (commented out) to define sites in models.py above. None of these worked.

event__sites is a ManyToManyField
You could try the following:
admin.py
def get_sites(self):
sites = self.event.sites.all()
result = u''
for site in sites:
result = u'%s - %s' % (result, site.name) # unsure about NAME - is it a valid field of Sites Model?
return result
get_sites.short_description = u'Sites'
class EventTimeAdmin(admin.ModelAdmin):
list_filter = ('event_date', get_sites)
admin.site.register(EventTime, EventTimeAdmin)
Hope it helps.

Related

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use technicians.set() instead

I keep getting this very same type error even though I am using set. Can someone maybe point out what I'm doing wrong in my api endpoint?
views.py
#require_http_methods(["GET", "POST"])
def api_requerimientos(request):
if request.method == "GET":
requerimientos = FormularioCliente.objects.all()
return JsonResponse(
{"requerimientos": requerimientos},
encoder=FormularioClienteEncoder,
)
elif request.method == "POST":
print("POST REQUEST HIT")
try:
content = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponseBadRequest("Invalid JSON in request body")
requerimiento = FormularioCliente(**content) # Create a new FormularioCliente object
if "technicians" in content and isinstance(content["technicians"], list):
try:
technicians_id_list = content["technicians"]
technicians = Technician.objects.filter(employee_number__in=technicians_id_list)
requerimiento.technicians.set(technicians)
requerimiento.save()
print('requerimiento:', requerimiento)
except Technician.DoesNotExist:
pass
requerimiento.save() # Save the object to the database
models.py
class FormularioCliente(models.Model):
empresa = models.CharField(max_length=21, null=True, unique=True)
titulo = models.CharField(max_length=66)
descripcion = models.CharField(max_length=66)
enlace = models.URLField(null=True)
tipo = models.CharField(max_length=17, choices=TIPO_REQUIRIMIENTO, default="tecnologia")
date = models.DateField(null=True, auto_now_add=True)
time = models.TimeField(null=True, auto_now_add=True)
entrega = models.DateField(null=True)
finished = models.CharField(max_length=19, choices=TIPO_FINALIZACION, default="Abierto")
technicians = models.ManyToManyField(Technician, blank=True)
special_hours = models.SmallIntegerField(default=0)
regular_hours = models.PositiveSmallIntegerField(default=1)
total_hours = models.SmallIntegerField(default=1)
importancia = models.PositiveSmallIntegerField(default=1)
file = models.FileField(upload_to='files', blank=True)
updated = models.DateField(auto_now=True)
def __str__(self):
return f'{self.titulo}: {self.descripcion} # {self.date}'
def technicians_as_json(self):
return list(self.technicians.all().values())
class Technician(models.Model):
name = models.TextField()
employee_number = models.SmallIntegerField(unique=True, primary_key=True)
def __str__(self):
return self.name + " - " + str(self.employee_number)
encoders.py
class TechnicianEncoder(ModelEncoder):
model = Technician
properties = ["name", "employee_number"]
class FormularioClienteEncoder(ModelEncoder):
model = FormularioCliente
properties = [
"id",
"empresa",
"titulo",
"descripcion",
# "user",
"enlace",
# "tipo",
# "File",
"tipo",
"date",
"time",
"entrega",
"finished",
"technicians", # <-- Add this
"special_hours",
"regular_hours",
"total_hours",
"importancia",
"updated",
]
encoders = {"technicians": TechnicianEncoder()}
I also tried to loop through technicians queryset and add it to the instance one by one as well via the add() method but that also didn't work.
I even tried this:
techs = list(requerimiento.technicians.filter(employee_number__in=technicians_id_list).all())
requerimiento.technicians.set(techs)
None of it worked

Django - Query from a sub-table

I have an application that has a dropdown menu among other things.
The menu is created based on the requirements. I wrote a query that checks the statuses and calculates how many requirements are in a given status. Then he builds a menu out of it. However, I have a problem because sometimes a requisition has been created but no items have been added to it. In that case, my menu shows this as one of the items. This is not what he expects. I would like the query to return and count only those requirements in a given status that have children.
Below I paste the model code and inquiries.
class D_DemandStatus(ModelBaseClass):
status = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50)
created_user = models.ForeignKey(User, on_delete=models.PROTECT)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.created_user = user
self.modified_by = user
super(D_DemandStatus, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Demand status'
verbose_name_plural = 'Demands status'
class Demand(models.Model):
name = models.CharField(max_length=500)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
self.modified_by = user
super(Demand, self).save(*args, **kwargs)
def __str__(self):
return self.name
def submitt(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='WAITING')
print(dict_status)
self.demanddetails_set.filter(demand_id = self.pk).update(status=dict_status)
self.status = dict_status
self.save()
def status_actualize(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='ORDERED')
items_status = DemandDetails.objects.filter(demand=self.pk).values('status').distinct()
if len(items_status) == 1 and items_status[0]['status'] == dict_status.id :
self.status = D_DemandStatus.objects.get(status='ORDERED')
#elif len(items_status) > 1 :
# self.status = D_DemandStatus.objects.get(status='INPROGRESS')
self.save()
class Meta:
verbose_name = 'Demand'
verbose_name_plural = 'Demands'
class DemandDetails(models.Model):
demand = models.ForeignKey(Demand, on_delete=models.CASCADE, related_name='items')
component = models.ForeignKey(Component, on_delete=models.CASCADE)
order_item = models.ForeignKey(OrderItem, null=True, on_delete=models.PROTECT, editable=False, related_name='demand_details_item')
quantity = models.IntegerField(default=1)
comment = models.CharField(max_length=150, blank=True)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(auto_now_add=True)
def quantityUpdate(self, val):
if self.pk :
self.quantity = val
self.save()
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
if not self.pk:
try:
super(DemandDetails, self).save(*args, **kwargs)
except IntegrityError as e:
obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id)
obj.quantity = obj.quantity + 1
obj.save()
else:
super(DemandDetails, self).save(*args, **kwargs)
def __str__(self):
return self.demand.name
class Meta:
verbose_name = 'Demand detail'
verbose_name_plural = 'Demand details'
constraints = [
models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' )
]
The query that works now looks like this:
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name')).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
In this case, however, even if the demand is empty (no items added), it is counted as 1
So I have changed the code a little, but it doesn't work as I would like, because it also counts the individual elements of the demand - which is obvious, because the query returns the subsequent rows that are counted.
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name'), piece=Count('demanddetails')).filter(Q(piece__gte=1)).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
I need to write the query in such a way that I get a list of statuses with numbers of demands only which have derived elements in DemandDetails. If a Demand exists but has no derived elements then it is not taken into account - rather it is counted as 0. This is important because in the extreme case there may be only one Demand which is empty and then I want to have information about it in the menu but with the number 0.
I hope I have managed to write clearly what I chaie.
Please help me to create a suitable query.
Regards

Update Successfully but Data not update in db. Django rest framework

I'm working on my final year project, and I need some help to understand what is actually happening, The problem is that: I hit the Update request through postman which gives the successful message for updating the data. but when I check my Database there is no updated data. I also did the debugging but there was no exception by which I can understand the problem Anyone can please help me?
I'm using
PgAdmin for my database.
Django==4.0.2
djangorestframework==3.13.1
djangorestframework-jwt==1.11.0
djangorestframework-simplejwt==5.0.0
psycopg2==2.9.3**.
My Models:
class Company(Base):
company_name = models.CharField(max_length=255, db_column='Company_Name')
company_email = models.EmailField(unique=True, max_length=255, db_column='company_email')
company_manager_name = models.CharField(max_length=255, db_column='Manager_Name')
company_address = models.CharField(max_length=255, db_column='Company_address')
about_company = models.TextField()
company_website = models.URLField(max_length=200)
is_active = models.BooleanField(default=True, db_column='IsActive', help_text='I will use this for enable/disable '
'a specific record')
class Meta:
db_table: 'Company'
def __str__(self):
return self.company_name
def save(self, *args, **kwargs):
try:
if not self.pk:
self.company_email = self.company_email.replace(" ", "").lower()
super().save()
except Exception:
raise
class Base(models.Model):
"""Following fields are abstract and will be use in All over the project Any time Anywhere"""
create_by = models.BigIntegerField(db_column='CreatedBy', null=True, blank=True, default=0)
create_on = models.DateTimeField(db_column='CreatedOn', auto_now_add=True)
modified_by = models.BigIntegerField(db_column='ModifiedBy', null=True, blank=True, default=0)
modified_on = models.DateTimeField(db_column='ModifiedOn', auto_now=True)
deleted_by = models.BigIntegerField(db_column='DeletedBy', null=True, blank=True, default=0)
deleted_on = models.DateTimeField(db_column='DeletedOn', auto_now=True)
status = models.BigIntegerField(db_column='Status', default=0, help_text='I will use this field for making'
'the status like pending approved and '
'for some other purpose by Default it is '
'Zero which has no meaning', )
class Meta:
abstract: True
serializer.py:
class CompanyUpdateSerializer(serializers.ModelSerializer):
company_name = serializers.CharField(required=True, allow_null=False, allow_blank=False)
company_email = serializers.CharField(required=True, allow_null=False, allow_blank=False)
company_manager_name = serializers.CharField(required=True, allow_null=False, allow_blank=False)
company_address = serializers.CharField(required=True, allow_null=False, allow_blank=False)
about_company = serializers.CharField(required=True, allow_null=False, allow_blank=False)
company_website = serializers.URLField(allow_blank=False, allow_null=False)
class Meta:
model = Company
fields = ['id', 'company_name', 'company_email', 'company_manager_name', 'company_address', 'about_company',
'company_website']
def update(self, instance, validated_data):
try:
instance.company_name = validated_data.get('company_name', instance.company_name)
instance.company_email = validated_data.get('company_email', instance.company_email)
instance.company_manager_name = validated_data.get('company_manager_name', instance.company_manager_name)
instance.company_address = validated_data.get('company_address', instance.company_address)
instance.about_company = validated_data.get('about_company', instance.about_company)
instance.company_website = validated_data.get('company_website', instance.company_website)
instance.save()
return instance
except Exception as e:
raise e
Views.py
def put(self, request, pk=None):
try:
id1 = pk
saved_company = Company.objects.get(pk=id1)
data = request.data
serializer = CompanyUpdateSerializer(instance=saved_company, data=data)
if serializer.is_valid():
serializer.save()
return self.send_response(success=True, code=f'200', status_code=status.HTTP_200_OK,
description='Company is updated')
return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
description=serializer.errors)
except ObjectDoesNotExist:
return self.send_response(code='422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
description="No Company matches the given query.")
except IntegrityError:
return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
description="Email Already Exist")
except Company.DoesNotExist:
return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
description="Company Model doesn't exists")
except FieldError:
return self.send_response(code=f'500', description="Cannot resolve keyword given in 'order_by' into field")
except Exception as e:
return self.send_response(code=f'500', description=e)
The problem comes from Company.save() method.
You overrode it as
class Company(Base):
...
def save(self, *args, **kwargs):
try:
if not self.pk:
self.company_email = self.company_email.replace(" ", "").lower()
super().save()
except Exception:
raise
Notice the call of super().save() inside the self.pk is None if statement block.
This will make the actual save method to be called only when the pk is None, meaning that only when a new instance is created, not when an instance is updated.
Moving the super().save() call to be outside the if statement should handle both creating and updating.
class Company(Base):
...
def save(self, *args, **kwargs):
try:
if not self.pk:
self.company_email = self.company_email.replace(" ", "").lower()
super().save(*args, **kwargs)
except Exception:
raise

Django Post request for many to many field ValueError

I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.
These are the models:
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
"""Return a human readable representation of the model instance."""
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Combination(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
tag_id = models.ManyToManyField(Tag, null=True)
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
objects = models.Manager()
def __str__(self):
return str(self.tag_id) or ''
This is the serializer for Combination.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag_id', None)
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
for tag_object in tag_data[0]:
combination.tag_id.add(tag_object)
return combination
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
return rep
I have tried posting the following JSON object to the database:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}
I am getting a ValueError: Field 'id' expected a number but got 'name'.
How can I fix this issue?
you need to provide tag id for each tag not all tag data,
Try like this
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [2014077506,2014077507]
}

How to create data to the database using views

I am trying to create order amount from the catalogue which works like a shopping cart but the amount returned is 1 for all orders made:
views.py
def get_user_pending_order(request):
#get order from correct profile
user_profile = get_object_or_404(Profile,user=request.user)
order = Order.objects.filter(owner=user_profile,is_ordered=True)
if order.exists():
#to get an order in the list of filtered orders
return order[0]
return 0
def add_to_catalogue(request,employee_id):#product_id,employee_id
user_profile= get_object_or_404(Profile, user =request.user)
order_to_purchase = get_user_pending_order(request)
amount= self.order_to_purchase.get_catalogue_total(),
employee = Employee.objects.get(pk=employee_id)
if employee in request.user.profile.ebooks.all():
messages.info(request,'you already own this ebook')
return redirect(reverse('freelance:employee_list'))
order_task,status =
OrderTask.objects.get_or_create(employee=employee)
user_order,status = Order.objects.get_or_create(owner=user_profile,
is_ordered=False,order_amount=amount)####TThis IS WHWERE TO EDIT TO PREVENT
RE ORDERNG OF FREELANCING
user_order.tasks.add(order_task)
if status:
user_order.ref_code = generate_order_id()
user_order.save()
messages.info(request,"task added to catalogue")
return redirect(reverse('freelance:employee_list'))
def get_user_pending_order(request):
#get order from correct profile
user_profile = get_object_or_404(Profile,user=request.user)
order = Order.objects.filter(owner=user_profile,is_ordered=True)
if order.exists():
#to get an order in the list of filtered orders
return order[0]
return 0
models.py
class Order(models.Model):
ref_code = models.CharField(max_length=15)
owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=
True)
is_ordered = models.BooleanField(default=False)
tasks = models.ManyToManyField(OrderTask)
date_ordered = models.DateTimeField(auto_now= True)
order_amount = models.DecimalField(default=0.01, max_digits= 10,
decimal_places=2)
def order_tasks(self):
return ','.join([str(c.employee) for c in self.tasks.all()])
def get_catalogue_tasks(self):
return self.tasks.all()
def get_catalogue_total(self):
return sum([task.employee.pricing for task in self.tasks.all()])
def __str__(self):
return '{0} - {1}'.format(self.owner, self.ref_code, self.order_amount)
def tasks_summary(request):
existing_order = get_user_pending_order(request)
my_user_profile = Profile.objects.filter(user=
request.user).first()
my_orders = Order.objects.filter(is_ordered= True, owner=
my_user_profile)
order_to_purchase = get_user_pending_order(request)
amount= order_to_purchase.get_catalogue_total(),
order = Order.objects.filter(is_ordered= True)
context = {
'my_orders':my_orders,
'order':order,
'amount':amount
# 'total':total,
}
return render(request,
'freelance/tasks_summary.html',context)###Belongs to the admin sisde
Output of the template
I am getting this error when I try to add anything to the catalogue:
AttributeError at /admin/tasks_summary/
'int' object has no attribute 'get_catalogue_total'

Resources