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]
- Multiply in django template
- How to access current user in Django class based view
- Django: Transaction and select_for_update()
- Installed Virtualenv and activating virtualenv doesn't work
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.
- Django – Form not valid but no error
- How to format Django's timezone.now()
- Django Rest Framework receive primary key value in POST and return model object as nested serializer
Source:stackexchange.com