[英]How to get list of related object in annotion when using Greatest function in django models
I am having two models, a User
model and a Payment
model and there is on to many relationship between them.我有两个模型,一个
User
模型和一个Payment
模型,它们之间有很多关系。 User
has multiple Payment
s. User
有多个Payment
。 What I am trying to achieve is sorting the User
model as per the Payment
's created_at
field.我想要实现的是根据
Payment
的created_at
字段对User
模型进行排序。
I am trying to modify the Queryset and then I'll be using the annotated field latest_tran
for sorting.我正在尝试修改查询集,然后我将使用带注释的字段
latest_tran
进行排序。
def get_queryset(self, request):
qs = super(ClubbedPaymentAdmin, self).get_queryset(request)
qs = qs.annotate(
latest_tran=Greatest(Payment.objects.filter(user=F('id')).values_list('created_at', flat=True)))
return qs
But I am having below error.但我有以下错误。
Greatest must take at least two expressions
So it seems like I am making a mistake when evaluating the list of Payment
s.因此,在评估
Payment
列表时,我似乎犯了一个错误。 Or may be like I am taking a wrong approach.或者可能就像我采取了错误的方法。 Any help would be much appreciated.
任何帮助将非常感激。 Thank you.
谢谢你。
Edit编辑
I am using the default User
model for users which are there in django
我正在为
django
用户使用默认的User
模型
My Payment
model looks like this -我的
Payment
模式是这样的 -
class Payment(models.Model):
amount = models.FloatField('Points', max_length=10)
purchase_token = models.TextField(max_length=250)
user = models.ForeignKey(User, on_delete=models.CASCADE)
note = models.TextField(max_length=1000, default=None, blank=True)
created_at = models.DateTimeField('Transaction Date')
updated_at = models.DateTimeField('Updated at', auto_now=True)
Greatest
does not take the maximum, it takes the largest of the different parameters , so Greatest('foo', 'bar')
will take the largest of the foo
and bar
column. Greatest
不取最大值,它取不同参数中的最大值,因此Greatest('foo', 'bar')
将取foo
和bar
列中的最大值。
What you need isMax
[Django-doc] .你需要的是
Max
[Django-doc] 。 You can make use of the name separated by an underscore, so:您可以使用由下划线分隔的名称,因此:
from django.db.models import
Max
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
latest_tran=Max('payment__created_at')
)
Note : It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly.注意:通常最好使用
settings.AUTH_USER_MODEL
[Django-doc]来引用用户模型,而不是直接使用User
模型 [Django-doc] 。 For more information you can see the referencing theUser
model section of the documentation .有关更多信息,您可以查看文档的引用
User
模型部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.