1

from the below table I need the output has,

[(Apple,21.0), (Orange,12.0) ,(Grapes,15.0) ]

basically fruits grouped with the sum of their cost

date in (dd/mm//yyyy)

Fruits Table
date        item    price
01/01/2021  Apple   5.0
01/01/2021  Orange  2.0
01/01/2021  Grapes  3.0
01/02/2021  Apple   7.0
01/02/2021  Orange  4.0
01/02/2021  Grapes  5.0
01/03/2021  Apple   9.0
01/03/2021  Orange  6.0
01/03/2021  Grapes  7.0
...........
....

models.py

 class Fruits(models.Model):
        item = models.CharField(max_length=32)
        date = models.DateField()
        price = models.FloatField()

I tried the below code its not working as expected

fruit_prices = Fruits.objects.filter(date__gte=quarter_start_date,date__lte=quarter_end_date)
               .aggregate(Sum('price')).annotate('item').values('item','price').distinct()
5
  • 1
    Can you share the model? Commented Jan 3, 2022 at 11:37
  • 1
    The filtering also looks odd: quarter_start_date is used twice? Commented Jan 3, 2022 at 11:38
  • Sorry its date__lte=quarter_end_date Commented Jan 3, 2022 at 11:42
  • 1
    can you share (relevant parts) of your model? Commented Jan 3, 2022 at 11:42
  • @WillemVanOnsem added model Commented Jan 3, 2022 at 11:44

1 Answer 1

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 prices 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].

Sign up to request clarification or add additional context in comments.

2 Comments

instead of order_by('item') it shouldn't be annotate ??
@SivaPerumal: yes. The total should be in the .annotate(..) clause. Forgot that .values(..) does not work with aggregates. Updated.

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.