Search code examples
djangodjango-modelsdjango-querysetdjango-database

Count same field values in Django queryset


I have a Django model with three fields: product, condition and quantity with data such as:

| Product | Condition | Quantity |
+---------+-----------+----------+
| A       | new       | 2        |
| A       | new       | 3        |
| A       | new       | 4        |
| A       | old       | 1        |
| A       | old       | 2        |
| B       | new       | 2        |
| B       | new       | 3        |
| B       | new       | 1        |
| B       | old       | 4        |
| B       | old       | 2        |

I'd like to sum the quantities of the entries where product and condition are equal:

| Product | Condition | Quantity |
+---------+-----------+----------+
| A       | new       | 9        |
| A       | old       | 3        |
| B       | new       | 6        |
| B       | old       | 6        |

This answer helps to count entries with the same field value, but I need to count two fields.

How could I implement this?


Solution

  • from django.db.models import Sum
    
    Model.objects.values('product', 'condition').order_by().annotate(Sum('quantity'))