Hi,
I am combining querysets of the same model in the following manner:
class ExampleModel(models.Model):
many_field1 = models.ManyToManyField('Model', related_name='name1')
many_field2 = models.ManyToManyField('Model', related_name='name2')
def combined_many_fields(self):
qs1 = self.many_field1.all().order_by('some', 'fields')
qs2 = self.many_field2.all().order_by('some', 'fields')
return qs1 | qs2
The result of the above code is that the order_by() methods are applied after the querysets are combined. This means that the two querysets can intermingle. I want them to be sorted before combination, not after, and retain being a queryset.
There are ways to force the evaluation of the individual querysets first and return a combination in the preferred order.
def combined_many_fields(self):
from itertools import chain
return chain(qs1, qs2)
However, this is no longer a queryset, and therefore cannot be operated on with subsequent queryset methods. Is there a way to apply the ordering first and retain the queryset nature of the combination?
Am I trying to do something that is outside the scope of a queryset?