简体   繁体   English

Django:TruncYear和注释/聚合?

[英]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. 我想知道每年的amount 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 ). Django返回一个查询集,其中包含数据库中每条记录的年份和总数(因此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')} ). Django返回总计( {'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. 我敢打赌,您在Order模型上指定了默认排序,这会导致您看到的行为。 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() . 注意order_by()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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