简体   繁体   中英

Django: TruncYear and annotate/aggregate?

I'm having the following model:

class Order(models.Model):
    placed_at = models.DateTimeField()
    amount = models.DecimalField()

And I want to know the total of amount for each year. When running:

Order.objects.annotate(year=TruncYear('placed_at'))
             .values('year')
             .annotate(total=Sum('amount'))

Django returns a queryset with the year and total for every record in the database (so total == amount ). When using aggregate:

Order.objects.annotate(year=TruncYear('placed_at'))
             .values('year')
             .aggregate(total=Sum('amount'))

Django returns the grand total ( {'total': Decimal('72822.41')} ). The result I'm looking for should be the total broken down per year. Like

<QuerySet [{'year': 2016, 'total': Decimal('20000.00')},
           {'year': 2017, 'total': Decimal('30000.00')}]

Any idea what I'm overlooking here?

I'm going to bet that you have a default ordering specified on your Order model, which would cause the behaviour you are seeing. You need to clear the default ordering when you make the query:

Order.objects.annotate(year=TruncYear('placed_at'))
         .values('year')
         .annotate(total=Sum('amount')).order_by()

Note the order_by() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM