[Answered ]-Django: order_by column from another table

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 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')

Leave a comment