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

Can I use select_related Django QuerySet method in reverse relationships?

class A(Model):
  pass


class B(Model):
  a = ForeignKey(A)


B.objects.select_related("a")  # this works
A.objects.select_related("b")  # this doesn't

How do I make the second line work? Are there any ways to do the same thing in some other ways?

>Solution :

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

You need to use prefetch_related since there could be multiple B instances referencing the same A instance

A.objects.prefetch_related("b_set")

https://stackoverflow.com/a/31237071/3862325

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related

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