[Django]-Product variants not reflecting updated quantity in Order Summary in a Django E-commerce Project

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)

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()
    ```

Leave a comment