Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django Cannot combine queries once a slice has been taken

is there any way to concatenate sliced querysets? its simplified example (i realize this particular example can be written in one query):

>>> ...
>>> query_set_1 = Model.objects.filter(...)[:3]
>>> query_set_2 = Model.objects.filter(...)[5:]

>>> query_set_1 | query_set_2

not going to work,

>>> AssertionError: Cannot combine queries once a slice has been taken.

any suggestions? thanks!

like image 326
StriveForBest Avatar asked Sep 18 '12 23:09

StriveForBest


2 Answers

No. But itertools.chain() will allow you to iterate through both querysets in order.

qiter = itertools.chain(query_set_1, query_set_2)
like image 109
Ignacio Vazquez-Abrams Avatar answered Oct 23 '22 05:10

Ignacio Vazquez-Abrams


You can use union() to combine two sliced queryset. Like this:

query_set_1 = Model.objects.filter(...)[:3]
query_set_2 = Model.objects.filter(...)[5:]

queryset = query_set_1.union(query_set_2)
like image 7
ruddra Avatar answered Oct 23 '22 03:10

ruddra