Combining querysets while maintaining desired ordering?

53 skatījumi
Pāriet uz pirmo nelasīto ziņojumu

Richard Brockie

nelasīta,
2017. gada 3. jūn. 20:20:1103.06.17
uz Django users
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?

Simon Charette

nelasīta,
2017. gada 3. jūn. 21:31:0203.06.17
uz Django users
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

Richard Brockie

nelasīta,
2017. gada 3. jūn. 22:16:3003.06.17
uz django-users
Hi Simon,

Thanks for the clarification of the operation of the .union() method - the operative phrase in the docs appears to be "combine the results of two or more QuerySets" - perfect!

My project is currently using 1.8 LTS - I can defer this until I roll forward to 1.11 LTS (hopefully sometime soon).

Thanks again,
R.


--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/au1f0zHq64M/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
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.



--
    R.

Richard Brockie

Real-time bicycle race results - www.ontheday.net
Atbildēt visiem
Atbildēt autoram
Pārsūtīt
0 jauni ziņojumi