[英]Making an alias for an attribute field, to be used in a django queryset
In Django, how does one give an attribute field name an alias that can be used to manipulate a queryset? 在Django中,如何赋予属性字段名称一个别名 , 该别名可用于操纵查询集?
Background: I have a queryset where the underlying model has an auto-generating time field called "submitted_on". 背景:我有一个查询集,其中基础模型具有一个自动生成的时间字段,称为“ submitted_on”。 I want to use an alias for this time field (ie "date").
我想为此时间字段使用别名(即“日期”)。 Why?
为什么? Because I will concatenate this queryset with another one (with the same underlying model), and then
order_by('-date')
. 因为我要将这个查询集与另一个查询集(具有相同的基础模型)连接起来,然后再与
order_by('-date')
。 Needless to say, this latter qset already has a 'date' attribute (attached via annotate() ). 不用说,后一个qset已经具有'date'属性(通过annotate()附加)。
How do I make a 'date' alias for the former queryset? 如何为前一个查询集创建“日期”别名? Currently, I'm doing something I feel is an inefficient hack:
qset1 = qset1.annotate(date=Max('submitted_on'))
目前,我正在做一些我觉得效率低下的事情:
qset1 = qset1.annotate(date=Max('submitted_on'))
I'm using Django 1.5 and Python 2.7 . 我正在使用Django 1.5和Python 2.7 。
Even if you could do this, it wouldn't help solve your ultimate problem. 即使您可以这样做,也无助于解决您的最终问题。 You can't use
order_by
on concatenated querysets from different models; 您不能对来自不同模型的串联查询集使用
order_by
; that can't possibly work, since it is a request for the database to do an ORDER BY on the query. 这可能行不通,因为这是数据库对查询执行ORDER BY的请求。
It seems qset1 = qset1.annotate(date=Max('submitted_on'))
is the closest I have right now. 看来
qset1 = qset1.annotate(date=Max('submitted_on'))
是我现在最接近的。 This, or using exclude()
. 这,或使用
exclude()
。 I'll update if I get a better solution. 如果有更好的解决方案,我会进行更新。 Of course other experts from SO are welcome to chime in with their own answers.
当然,欢迎来自SO的其他专家提出自己的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.