3π
Of course, to django both those items are the same.
The lines responsible for this are:
if order_item_qs.exists():
order_item = order_item_qs.first() # Here, you are always picking the first item that your filter returned, see: https://docs.djangoproject.com/en/dev/ref/models/querysets/#first
order_item.quantity += 1
order_item.save()
As taken from https://docs.djangoproject.com/en/dev/ref/models/querysets/#first :
first()ΒΆ
Returns the first object matched by the queryset, or None if there is
no matching object. If the QuerySet has no ordering defined, then the
queryset is automatically ordered by the primary key. This can affect
aggregation results as described in Interaction with default ordering
or order_by().
However, the main culprit is:
order_item_qs = OrderItem.objects.filter(
item=item,
user=request.user,
ordered=False
)
You want to pass the variation to it, e.g.
order_item_qs = OrderItem.objects.filter(
item=item,
user=request.user,
ordered=False,
variation=variation
)
You could consider adding the size as a field of product and creating individual products based on the variations. However, simply retrieving the variation and making sure you only increment the correct item by passing it to your filter() is also a correct approach.
0π
order_item_qs = order_item_qs.filter(
Q(item_variations__exact=v)
)
with:
order_item_qs = order_item_qs.filter(item_variations__variation=v)
- [Django]-Django AttributeError: 'InterestsForm' object has no attribute '_errors'
- [Django]-Celery receives tasks from rabbitmq, but not executing them
- [Django]-Django multiple forms with modelchoicefield -> too many queries
0π
I think the problem in block
if order_item_qs.exists():
order_item = order_item_qs.first()
order_item.quantity += 1
order_item.save()
this block of code gets executed only once
you need to rewrite it to
if len(item_var) > 0:
for items in item_var:
order_item_qs = OrderItem.objects.filter(
item=item,
user=request.user,
ordered=False
).filter(variation__exact=items,)
if order_item_qs.exists():
order_item = order_item_qs.first()
order_item.quantity += 1
order_item.save()
else:
order_item = OrderItem.objects.create(
item=item,
user=request.user,
ordered=False
)
order_item.variation.add(*item_var)
order_item.save()
```
- [Django]-TypeError: get() takes 2 positional arguments but 3 were given
- [Django]-Custom Django 404 page and Django debug page
- [Django]-Save svg to tempfile Python
- [Django]-Sudo equivalent for Django user profiles
- [Django]-Django DRF create user