Child.objects.select_related("parent").filter(parent=parent_instance)
or Child.objects.filter(parent=parent_instance).select_related("parent")
which one is less time consuming
I am not sure which one is taking minimum queries and improve performance
Both will result in the same query. It is not necessary to .select_related(…)
[Django-doc] or .prefetch_related(…)
[Django-doc] to filter. If you filter on a related item, it will just make JOINs.
The idea of .select_related(…)
is only to add the related models in the SELECT
clause and to prevent making a query when obtaining the .parent
attribute of any of the Child
s that arise from the queryset.
Depending on the use-case, you thus might not need to select the parent in the clause, for example if you only will render fields of the Child
objects, in that case, the most efficient is thus:
Child.objects.filter(parent=parent_instance)
or:
parent_instance.child_set.all()