Django N+1 query solution

匆匆过客 提交于 2019-12-04 00:18:49

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.

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]
Jeremy Cumbo

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!