[Django]-How annotate the Max value of two fields in a Django QuerySet

39👍

Thanks to Robert’s answer i was able to find Greatest class of Django.

The following works:

from django.db.models.functions import Greatest

Client.objects.annotate(
    latest_activity_at=Greatest('uploaded_photo_at', 'uploaded_document_at')
).order_by('latest_activity_at')

2👍

Hi you can use django query extra function

qs = Client.objects.extra(select={'output_field': 
                                 'GREATEST(uploaded_photo_at, uploaded_document_at)'})
                   .order_by('latest_activity_at')

This will return max value two fileds

👤Robert

Leave a comment