I have 2 models namely A and B. Both have a common field, say timestamp.
X = A.objects.all()
Y = A.objects.all()
results = chain(X,Y) # Union
Now I want to apply ORDERBY query on results
. How can I do that?
I have 2 models namely A and B. Both have a common field, say timestamp.
X = A.objects.all()
Y = A.objects.all()
results = chain(X,Y) # Union
Now I want to apply ORDERBY query on results
. How can I do that?
While the python way of doing it is by using some kind of sorting, this is normally not the correct way of doing it in Django.
The reason is that in order to join two queries of two different models, you have to transform them to lists (as other answers suggest).
While this seems good, most of the time it is not, because you hit the database, i.e. the database is asked for all elements of both models for creating both lists, and them joining.
The most likely reason why you are joining two models in a single list is because both should be derived from a common model, e.g. an Abstract model. Doing this both models have a natural common field obtained by being subclasses of the abstract model.
The ordering of such a query can then be made using order_by. This is more efficient because queries are lazy.
EDIT:
Example:
class Parent(models.Model):
date_field = models.DateField()
def pretty_show():
# returns general behavior
class B(Parent):
# other specific fields
def pretty_show():
# returns specific behavior
class C(Parent):
# other specific fields
def pretty_show():
# returns specific behavior
X = Parent.objects.all().order_by("date_field")
for x in X:
x.pretty_show()
Notice that Parent class in this case is not Abstract and childs are not proxies, but this choice strongly depends on what you want to achieve. Hope this helps.
You could try to create a list of the model objects and then sort by their time stamp like this (both models must have the same time_stamp attribute):
l= list(x)+list(y)
l.sort(key=lambda l: l.time_stamp)
Hope this is what you are looking for.