2017-09-14 61 views
3

註釋兩個領域的最高值我有一個模型Client,我怎麼編序排序,它的兩個字段的最大:如何在Django的QuerySet

from django.db import models 

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

以下:

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

引發此錯誤:

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. 

我使用Posgresql和Django的1.11,是否有幫助。

回答

3

感謝返回最大值羅伯特的回答我能找到Greatest類的Django的。

以下工作:

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

嗨,你可以使用Django 查詢額外功能

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

這個域中