Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a model Client, how do i annotate then sort, the Max of its two fields:

from django.db import models

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

The following:

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

Raises 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 am using Posgresql and Django 1.11, if that helps.

like image 849
A. K. Tolentino Avatar asked Sep 14 '17 03:09

A. K. Tolentino


People also ask

What is difference between annotate and aggregate Django?

Unlike aggregate() , annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet ; this QuerySet can be modified using any other QuerySet operation, including filter() , order_by() , or even additional calls to annotate() .

What is QuerySet annotate?

In simpler terms, annotate allows us to add a pseudo field to our queryset. This field can then further be used for filter lookups or ordering.\ Ex: Suppose you want to all the Books along with the total number of chapters present in each one, then you could use annotate as follows: Simple annotate example.

How does annotate work in Django?

Django annotations 2 are a way of enriching the objects returned in QuerySets. That is, when you run queries against your models you can ask for new fields, whose values will be dynamically computed, to be added when evaluating the query. These fields will be accessible as if they were normal attributes of a model.

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.


1 Answers

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')
like image 125
A. K. Tolentino Avatar answered Oct 15 '22 20:10

A. K. Tolentino