[Answer]-How to improve the following query

1👍

Use prefetch_related(); select
_related()
doesn’t work on ManyToManyFields:

providers = Provider.objects.order_by('provider').all().prefetch_related('userprofile_set')

From the docs:

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related.

0👍

I’m not using django but i just found the answer here: docs.djangoproject.com

providers = Provider.objects.select_related().order_by('provider').all()
👤Besnik

Leave a comment