简体   繁体   中英

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?

Background: I have a queryset where the underlying model has an auto-generating time field called "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') . Needless to say, this latter qset already has a 'date' attribute (attached via 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'))

I'm using Django 1.5 and 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; that can't possibly work, since it is a request for the database to do an ORDER BY on the query.

It seems qset1 = qset1.annotate(date=Max('submitted_on')) is the closest I have right now. This, or using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM