Question: One of my querysets returns list of items with several fields:

```
<QuerySet [{'name': 'John', 'products': 4}, {'name': 'John', 'products': 6}, {'name': 'Sam', 'products': 7}, ...]>

```

How do I aggregate this data to get combined `Sum()` of `products` value for elements with the same `name` field to avoid duplicates in queryset, so as a result I'll have something like this:

```
<QuerySet [{'name': 'John', 'products': 10}, {'name': 'Sam', 'products': 7}, ...]>

```

I understand this should be done using `.annotate()` or `.aggregate()` queries but I can't figure out how.

Answer: 
You can construct such queryset with:

```
from django.db.models import Sum

Model.objects.values('name').annotate(
    **sum\_products=Sum('products')**
).order_by(**'name'**)
```

The `.order_by(..)` is necessary to force Django to use a GROUP BY clause.
What you need is `annotate`, and you can do something like this:

```py
from django.db.models import Sum

your_queryset = YourModel.objects.annotate(total_products=Sum('products')).values_list('name', 'total_products')

```

You can learn more about it by looking at the [docs](https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset)