Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

query optimization and improve performance

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 Childs 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading