Late, and the previous answers do not solve my specific question, but they led me to the answer, so I'm going to throw this at:
I need to sort prefetch_related objects for only one view, so changing the order by default is not suitable (maybe model_manager will do this, idk). But I found this in the docs .
I have the following models:
class Event(models.Model): foo = models.CharField(max_length=256) .... class Session(models.Model): bar = models.CharField(max_length=256) event = models.ForeignKey(Event) start = models.DateTimeField() .... class Meta: ordering = ['start']
Now in a specific view I want to see all Event s, but I want their Session in reverse order, i.e. ordering = ['-start']
So, I do this in the get_queryset() :
from django.db.models import Prefetch session_sort = Session.objects.all().order_by('-start') prefetch = Prefetch('sessions', queryset=session_sort) events = Event.objects.all().prefetch_related(prefetch)
Hope this helps someone!
* BTW, This is just a simplified version, in my actual use there are many filters and other prefetch_related parameters.
Rob l source share