Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

Django - Group by Count of Foreign Key

I have two models like so:

models.py

class Subscription(...):
    is_active = models.BooleanField(...)

class Order(...):
    subscription = models.ForeignKey('Subscription', related_name='orders', ...)
    ...

I want to know:

  1. How many subscriptions have x number of orders (i.e. 2 subscriptions with 1 order, 3 subscriptions with 2 orders, etc.)
  2. The average number of orders across all of my subscriptions (i.e. 1.6 orders)

I can susccesfully annotate the number of orders to a subscription queryset, but I am having trouble grouping the queryset by like number_of_orders from there:

views.py

from django.db.models import Count

queryset = Subscription.objects.filter(is_active=True).annotate(number_of_orders=Count('orders')
queryset = queryset.values('number_of_orders')

Which gets me something like: <QuerySet [{'number_of_orders': 1}, {'number_of_orders': 2}, {'number_of_orders': 1}, {'number_of_orders': 2}, {'number_of_orders': 2}]>

I am looking for a final result that looks something like:

<QuerySet [{"number_of_orders" : 1, "subscriptions_count" : 2}, {"number_of_orders" : 2, "subscriptions_count" : 3}]>

I've tried:

queryset = queryset.order_by('number_of_orders').aggregate(subscriptions_count=Count('number_of_orders'))

which doesn't group my subscriptions correctly, and:

queryset = queryset.order_by('number_of_orders').annotate(subscriptions_count=Count('number_of_orders'))

which fails with this error:

Cannot compute Count('number_of_orders'): 'number_of_orders' is an aggregate
question from:https://stackoverflow.com/questions/65924531/django-group-by-count-of-foreign-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...