[Fixed]-Django prefetch_related a large dataset

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

Leave a comment