For Loop to Find Matching Values and Total in Python

Viewed 78

I have a Django project where my Manifests model consists of item codes and quantity. I want to loop through the model and find the total quantity for each item code. So I have the following in my view:

manifest = Manifests.objects.all()

How could I use a for loop or something to total the quantity for each item code. Or more clearly, if item code 10 is there 3 times with quantities = 1, 2, and 3. Total should be 6 for item code 10, and if item code 20 is there twice with quantities = 2 and 5 total should be 7.

Here is the model for reference:

models.py

class Manifests(models.Model):
    reference = models.IntegerField()
    quantity = models.IntegerField()
    item_code = models.ForeignKey(Products, default=None, blank=True, null=True)
1 Answers

Please do not use for loops. You can annotate your queryset of Products with:

from django.db.models import Sum

Products.objects.annotate(
    total_quantity=Sum('manifests__quantity')
)

The Products objects that arise from this queryset will have an extra attribute .total_quantity that will contain the sum of the .quantitys of the related Manifestss objects.

Or you can count only the Manifests objects with reference=10 with:

from django.db.models import Sum, Q

Products.objects.filter(
    Q(manifests=None) | Q(manifests__reference=10)
).annotate(
    total_quantity=Sum('manifests__quantity')
)

Note: usually the name of a model is singular, so Manifest instead of Manifests, and Product instead of Products.

Related