如何在Django QuerySet中注释两个字段的Max值

时间:2022-05-16 15:21:47

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.

我正在使用Posgresql和Django 1.11,如果有帮助的话。

2 个解决方案

#1


6  

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

感谢Robert的回答,我能够找到最好的Django类。

The following works:

以下作品:

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

#2


2  

Hi you can use django query extra function

嗨,你可以使用django查询额外的功能

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

这将返回最大值两个文件

#1


6  

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

感谢Robert的回答,我能够找到最好的Django类。

The following works:

以下作品:

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

#2


2  

Hi you can use django query extra function

嗨,你可以使用django查询额外的功能

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

这将返回最大值两个文件