Filter Django queryset with multiple variables

cr1

I would like to pass one or many GET variables to filter a queryset. I have tried the following code to create a dictionary of the variables and apply the filter, but testing with two variables it appears to only be filtering on the final dictionary variables.

for k,v in mydict.items():
    qs = mymodel.objects.filter(**{"%s__contains" % k: v})

Can anyone point me in the right direction as to where I am going wrong?

Selcuk

You are creating a new queryset in each iteration from scratch instead of chaining them. Try changing your code to:

qs = mymodel.objects.all()
for k, v in mydict.items():
    qs = qs.filter(**{"%s__contains" % k: v})

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related