[Django]-Why django models make many small queries instead of one large?

9👍

Django gets only the data you ask it to get. You can use select_related() and prefetch_related() to ask it to get all the data in a single query using JOINs.

Quoting docs:

select_related(*fields)

Returns a QuerySet that will “follow”
foreign-key relationships, selecting additional related-object data
when it executes its query. This is a performance booster which
results in a single more complex query but means later use of
foreign-key relationships won’t require database queries.

prefetch_related(*lookups)

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

Leave a comment