Home How annotate the Max value of two fields in a Django QuerySet
Reply: 2

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

GheloAce
1#
GheloAce Published in 2017-09-14 03:39:25Z

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.

Robert
2#
Robert Reply to 2017-09-14 04:32:30Z

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

GheloAce
3#
GheloAce Reply to 2017-09-14 06:09:43Z

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

The following works:

Client.objects.annotate(
    latest_activity_at=Greatest('uploaded_photo_at', 'uploaded_document_at')
        ).order_by('latest_activity_at')
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301805 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO