1

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 (i.e. "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.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
  • You're going to try to concatenate QuerySets which contain two different types? – dursk Oct 17 '15 at 14:36
  • No no, same type, read my comment to Daniel's answer below. – Hassan Baig Oct 17 '15 at 15:00
  • Edited to add more clarity to the question – Hassan Baig Oct 17 '15 at 15:03
  • Have you considered just doing the sorting in python rather than sql? – dursk Oct 17 '15 at 15:05
  • The dataset isn't small. I need this for a chatting app, the qsets are made up of sentences people are saying (each person says ~700 sentences a day, there are ~1200 users per day, and growing). Would a python sort be recommended, wouldn't database sort be faster? – Hassan Baig Oct 17 '15 at 15:09

2 Answers2

0

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Actually Daniel, both querysets will have been extracted from the **SAME** model. I simplified that out from this question, though if you want to read the gory details, head here and read my question till step (3): http://stackoverflow.com/questions/33137706/tricky-django-queryset-creation-concatenation-and-sorting-issue-with-complex-fo – Hassan Baig Oct 17 '15 at 15:00
  • Edited the question and added more clarity to it – Hassan Baig Oct 17 '15 at 15:02
0

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.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205