0👍
✅
I fixed it this way:
from django.db.models import Max
from django.db.models.functions import Coalesce
Discussion.objects.alias(
latest_reply=Coalesce(
Max('response__date_publication'), 'date_publication')
).order_by('-latest_reply')
1👍
You can order with:
from django.db.models import Max
from django.db.models.functions import Coalesce
Discussion.objects.alias(
latest_reply=Coalesce(Max('response__reply_to__date_publication'), 'date_publication')
).order_by('-latest_reply')
or for django-3.1 and earlier:
from django.db.models import Max
from django.db.models.functions import Coalesce
Discussion.objects.annotate(
latest_reply=Coalesce(Max('response__reply_to__date_publication'), 'date_publication')
).order_by('-latest_reply')
Source:stackexchange.com