[Django]-Django: Query with foreign key

5👍

You can annotate these with the Max aggregate [Django-doc], and use the Coalesce function [Django-doc] as a fallback mechanism, like:

from django.db.models import Max
from django.db.models.functions import Coalesce

Thread.objects.annotate(
    latest_post=Coalesce(Max('post__created_at'), 'created_at')
).order_by('-latest_post')

The latest_post is thus the timestamp of the maximum created_at of the related Post objects. In case there are no related Post objects, we fallback on the created_at field of the Thread.

Leave a comment