1π
β
Letβs imagine we have a few clients, something like 200, but they buy
a lot so we have millions of purchases.If I have to create a webpage displaying all the clients and the
number of purchases for each client, β¦
Iβm going to interpret your question as wanting this functionality. Have you tried:
from django.db.models import Count
clients = Client.objects.annotate(num_purchases=Count('purchase'))
clients[0].num_purchases
If you want to sort and get the highest purchasing clients, you can also do:
clients = Client.objects.annotate(num_purchases=Count('purchase')).order_by('-num_purchases')[:5]
See https://docs.djangoproject.com/en/1.11/topics/db/aggregation/ for more functionality.
π€user20061
Source:stackexchange.com