Django - Ordering by a foreign key
<p>I have a class that's called Movie:</p>

<pre><code>class Movie(models.Model):
    title = models.CharField(max_length=511)
    tmdb_id = models.IntegerField(null=True, blank=True, unique=True)
    release = models.DateField(null=True, blank=True)
    poster = models.TextField(max_length=500, null=True)
    backdrop = models.TextField(max_length=500, null=True, blank=True)
    popularity = models.TextField(null=True, blank=True)
</code></pre>

<p>and a class named Trailer:</p>

<pre><code>class Trailer(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    link = models.CharField(max_length=100)
    date = models.DateTimeField(auto_now_add=True)
</code></pre>

<p>How can I display all movies ordered by the date of the trailer?</p>

<p>I have tried: <code>Movie.objects.order_by('trailer__date')</code> but that causes multiple duplicates and doesn't show them on the right order either, how can I avoid the duplicates and have one entry per each movies ordered by the date of the Trailer object?</p>

<p><strong>Edit:</strong> I just noticed that it doesn't display all entries but just some of them</p>

<p>@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:</p>

<pre><code>from django.db.models import Max

qs = Movie.objects.annotate(Max("trailer__date")).order_by('-trailer__date__max')
</code></pre>

python django