Home > Net >  Can I use select_related Django QuerySet method in reverse relationships?
Can I use select_related Django QuerySet method in reverse relationships?

Time:02-10

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?

CodePudding user response:

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

  • Related