[Django]-Django – Ordering by a foreign key

2👍

@2ps answer was close but didn’t work as I would have liked, whether it was for ascending or descending order, but I finally figured out an answer based on his:

from django.db.models import Max

qs = Movie.objects.annotate(Max("trailer__date")).order_by('-trailer__date__max')
👤mari

4👍

Update: the OP wanted this sorted by the latest trailer date, and not by the earliest trailer date.

You can use annotate here if you want:

from django.db.models import Max
qs = Movie.objects.values('title').annotate(latest_trailer=Max('trailer__date')).order_by('-latest_trailer')
# Add other columns you want into the `values` if you need them

Or you can use your original query and couple it with a dict.

from collections import OrderedDict
qs = Movie.objects.order_by('-trailer__date')
movies = OrderedDict()
for x in qs:
    if x.id not in movies:
        movies[x.id] = x
movies = movies.values()

It was unclear what order you wanted the movies in when they had multiple trailers, so I guessed it was based on the earliest trailer.

👤2ps

Leave a comment