Hello Richard,
Since Django 1.11 you should be able to use the QuerySet.union() method[0]
for that.
queryset = self.many_field1.order_by('some', 'fields')
combined = queryset.union(self.many_field2.order_by('some', 'fields'))
Best,
Simon
[0] https://docs.djangoproject.com/en/1.11/ref/models/querysets/#union
Le samedi 3 juin 2017 20:20:11 UTC-4, Richard Brockie a écrit :
>
> 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?
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/5631ac9b-17a6-401d-9b2b-841440daf7f7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.