Ad

Ordering By First Foreign Key In Django

Consider these two simple models:

from django.db import models

class Foo( models.Model ):
  pass

class Bar( models.Model ):
  time = models.DateTimeField( auto_now_add=True )
  foo = models.ForeignKey(
    Foo,
    on_delete=models.CASCADE
    related_name='bars'
  )

How can I order Foo objects by first related Bar object?

Foo.objects.order_by('-bars.first__time')
Ad

Answer

Given that the "first" is the Bar object with the "oldest" time, we can first .annotate(..) our Foo objects, and then order on that minimum. We thus first annotate with Min(..), and then use that annotation:

from django.db.models import Min

Foo.objects.annotate(
    min_time=Min('bars__time')
).order_by('-min_time')
Ad
source: stackoverflow.com
Ad