Specifying order_by on Related Field in Django
<p>In Django, on a given model it looks like the <code>RelatedManager</code> may only be set statically (<a href="https://docs.djangoproject.com/en/1.9/topics/db/managers/#managers-for-related-objects" rel="nofollow">see: docs</a>) but is there any way to set the <code>order_by</code> on the related manager for a given Queryset? I tried using <code>prefetch_related</code> and <code>Prefetch</code>, but that does not seem to work:</p>

<pre><code>qs = qs.prefetch_related(
   Prefetch('item_set', queryset=Item.objects.order_by('capture_dt').all()))

res = qs.first().item_set.all().ordered
</code></pre>

<p>In this case <code>res</code> is <code>False</code>.</p>

<p>The problem comes when I try to access the related manager: accessing w/o <code>order_by</code> does not call another SQL query whereas if I then try to <code>order_by</code>, an additional query is executed which causes an <code>N + 1</code> SQL queries to be executed.</p>

<p>These two lines return the same results but the first generates far fewer SQL queries:</p>

<pre><code>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)
</code></pre>