4

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?

1 Answer 1

6
from django.db.models import Sum

Model.objects.values('product', 'condition').order_by().annotate(Sum('quantity'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.