In Django, on a given model it looks like the RelatedManager
may only be set statically (see: docs) but is there any way to set the order_by
on the related manager for a given Queryset? I tried using prefetch_related
and Prefetch
, but that does not seem to work:
qs = qs.prefetch_related(
Prefetch('item_set', queryset=Item.objects.order_by('capture_dt').all()))
res = qs.first().item_set.all().ordered
In this case res
is False
.
The problem comes when I try to access the related manager: accessing w/o order_by
does not call another SQL query whereas if I then try to order_by
, an additional query is executed which causes an N + 1
SQL queries to be executed.
These two lines return the same results but the first generates far fewer SQL queries:
r0 = [x.pk for x in sorted(self.parent.item_set.all(), key=lambda s: s.capture_dt)].index(self.pk)
r1 = list(x.pk for x in self.parent.item_set.order_by('capture_dt').all()).index(self.pk)