[Fixed]-Django N+1 query solution

13👍

You can do it with prefetch_related since Django 1.4:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

If you’re using < 1.4, have a look at this module:
https://github.com/ionelmc/django-prefetch

It claims to be more flexible than Django’s prefetch_related. Verbose but works great.

9👍

Unfortunately, Django’s ORM as of yet has no way of doing this.

Fortunately, it is possible to do it in only 2 queries, with a bit of work done in Python.

clients = list(Client.objects.all()[:10])
addresses = dict((x.client_id, x) for x in
    Address.objects.filter(client__in=clients))
for client in clients:
  print client, addresses[client.id]

2👍

django-batch-select is supposed to provide an answer to this problem, though I haven’t tried it out. Ignacio’s answer above seems best to me.

Leave a comment