简体   繁体   English

使用多个变量过滤Django查询集

[英]Filter Django queryset with multiple variables

I would like to pass one or many GET variables to filter a queryset. 我想传递一个或多个GET变量来过滤查询集。 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? 任何人都可以指出我在哪里出错了吗?

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM