Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to concatenate QuerySets?

Tags:

python

django

After a search of a database I end up with an array of querysets. I wanted to concatenate these queryset somewhat like we can do with list elements. Is this possible or maybe there an altogether better way to do this? The end goal here is to get queryset for rows of table that contain one of a set of strings in a field.

for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    myQuerySetTwoD.append(my.objects.filter(asn=filterString))
    for j in range(0,(len(myQuerySetTwoD)-1)):
        myQuerySet = myQuerySet + myQuerySetTwoD[j]

UPDATE: Found my own answer (something about writing the question down maybe)

Just

from itertools import chain

then replace

myQuerySet = myQuerySet + myQuerySetTwoD[j]

with

BgpAsnList = chain(BgpAsnList,BgpAsnListTwoD[j])
like image 762
evolution Avatar asked Dec 13 '11 11:12

evolution


1 Answers

I think the proper way to do that is to use the | operator (that is, if the QuerySets are of the same type):

qset = MyModel.objects.none()
for filterString in list_of_filterStrings:
    qset_temp = MyModel.objects.filter(asn=filterString)
    qset = qset | qset_temp
like image 100
mccc Avatar answered Oct 07 '22 16:10

mccc