How to annotate Max value for two fields in QuerySet Django

I have a model of Clienthow I can annotate and then sort, Max of two of its fields:

from django.db import models

class Client(models.Model):
    uploaded_photo_at = models.DateTimeField()
    uploaded_document_at = models.DateTimeField()

Following:

Client.objects.annotate(
    latest_activity_at=Max('uploaded_photo_at', 'uploaded_document_at', output_field=DateTimeField())
).order_by('latest_activity_at')

Causes this error:

django.db.utils.ProgrammingError: function max(timestamp with time zone, timestamp with time zone) does not exist
LINE 1: ...oto_at", "clients_client"."uploaded_document_at", MAX("clien...
                                                             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

I use Posgresql and Django 1.11 if this helps.

+6
source share
2 answers

Thanks to Robert's answer, I was able to find Greatestthe Django class.

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

Hi, you can use the 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 the maximum value for the two fields.

+2
source

Source: https://habr.com/ru/post/1685641/


All Articles