1👍
✅
You can work with a GROUP BY with:
from django.db.models import Sum
Fruits.objects.filter(
date__range=(quarter_start_date, quarter_end_date)
).values('item').annotate(
total=Sum('price')
).order_by('item')
This will generate a queryset that looks like:
<QuerySet [
{'item': 'Apple', 'total': 21.0},
{'item': 'Grapes', 'total': 15.0},
{'item': 'Orange', 'total': 12.0}
]>
a collection of dictionaries where the keys 'item'
and total
map to the item and the sum of all the price
s for that item
that satisfy the given datetime range.
I would however advise to make a FruitItem
model and work with a ForeignKey
, to convert your database modeling to the Third Normal Form [wiki].
Source:stackexchange.com