简体   繁体   English

Django ORM - 按子查询分组和注释

[英]Django ORM - Group by and annotate with subquery

What I'm trying to do in Django ORM is the following:我在 Django ORM 中尝试做的事情如下:

  • Group by user按用户分组
  • Sum the profits总结利润
  • Annotate with the latest status of that user使用该用户的最新状态进行注释

My queryset looks like this:我的查询集如下所示:

Sales.objects.values('user').annotate(
    profits = Sum('profit'),
    status = Subquery(Status.objects.filter(username=OuterRef('user')).order_by('-date').values('status')[:1]
).order_by()

If I inspect the SQL query of this queryset, I can see that the status field is added to the group by clause.如果我检查此查询集的 SQL 查询,我可以看到status字段已添加到group by子句中。 But this query cannot be executed.但是这个查询无法执行。 How can I prevent Django from adding this to the group by clause?如何防止 Django 将此添加到group by子句? Because the rest of the query just works fine.因为查询的 rest 工作正常。

Start with a User object rather than a Sales object.从用户 object 而不是销售 object 开始。

I don't know your model structure, so this is a bit of a guess.我不知道你的 model 结构,所以这有点猜测。

User.objects.annotate(
    profits = Sum('sales__profit'),
    status = Subquery(Status.objects.filter(username=OuterRef('user')).order_by('-date').values('status')[:1]).order_by()

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

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