0
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?

1 Answers1

0

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

Jimmy Pells
  • 674
  • 1
  • 5
  • 12
  • Thanks. What should I do if I want to sort the QS by a field of related set, i.e. `.prefetch_related("b_set").order_by("b_set__field")`? It does not work – aafbsyaqwiussmqlrc Feb 09 '22 at 15:50
  • each `B` in `b_set` could have a different value for `field` but you can do `.prefetch_related("b_set").order_by("b__field")` – Jimmy Pells Feb 09 '22 at 16:33