简体   繁体   中英

Django ORM - Group by and annotate with subquery

What I'm trying to do in Django ORM is the following:

  • 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. But this query cannot be executed. How can I prevent Django from adding this to the group by clause? Because the rest of the query just works fine.

Start with a User object rather than a Sales object.

I don't know your model structure, so this is a bit of a guess.

User.objects.annotate(
    profits = Sum('sales__profit'),
    status = Subquery(Status.objects.filter(username=OuterRef('user')).order_by('-date').values('status')[:1]).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