I’m wondering if there’s a difference in the order of operations or processing speed between
list( model.objects.filter().prefetch_related() )
and list( model.objects.prefetch_related().filter() ) .
Has anyone tested this?
I’m wondering if there’s a difference in the order of operations or processing speed between
list( model.objects.filter().prefetch_related() )
and list( model.objects.prefetch_related().filter() ) .
Has anyone tested this?
There should be no difference.
Quoting from the docs for prefetch_related
The additional queries in
prefetch_related()are executed after theQuerySethas begun to be evaluated and the primary query has been executed.
You can test and evaluate this yourself using the Django shell and looking at the queries being issued using connection.queries
For example:
In [39]: reset_queries()
In [40]: users=list(User.objects.filter(username__startswith='K').prefetch_related('groups').only('id', 'username'))
In [41]: connection.queries
Out[41]:
[{'sql': 'SELECT "auth_user"."id", "auth_user"."username" FROM "auth_user" WHERE "auth_user"."username"::text LIKE \'K%\'',
'time': '0.001'},
{'sql': 'SELECT ("auth_user_groups"."user_id") AS "_prefetch_related_val_user_id", "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "auth_user_groups" ON ("auth_group"."id" = "auth_user_groups"."group_id") WHERE "auth_user_groups"."user_id" IN (18, 8, 3)',
'time': '0.001'}]
and
In [43]: reset_queries()
In [44]: users=list(User.objects.prefetch_related('groups').filter(username__startswith='K').only('id', 'username'))
In [45]: connection.queries
Out[45]:
[{'sql': 'SELECT "auth_user"."id", "auth_user"."username" FROM "auth_user" WHERE "auth_user"."username"::text LIKE \'K%\'',
'time': '0.001'},
{'sql': 'SELECT ("auth_user_groups"."user_id") AS "_prefetch_related_val_user_id", "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "auth_user_groups" ON ("auth_group"."id" = "auth_user_groups"."group_id") WHERE "auth_user_groups"."user_id" IN (18, 8, 3)',
'time': '0.001'}]
You can see that the same two queries are executed each time.
Is a similar query passed even in a regular call without using .only?
Try it and see! That’s the best way to learn about such things.