繁体   English   中英

任意数量的搜索词

[英]Arbitrary number of search terms

我正在尝试创建一个视图,该视图将采用任意数量的搜索词,并使用这些词过滤特定的对象。

我在想的是,该网址将具有类似于以下内容的模式: /[property]=[value]/[property]=[value]/...在这种模式下,这种情况可以持续很长时间用户想要的。 然后,我可以通过执行以下操作来解析此内容: search=match.split('/') 然后,我将遍历搜索中的每个项目,具体内容如下:

results=myObject.objects.all()
for item in search:
    items=item.split('=')
    results=results.filter(items[0]=items[1])

不幸的是,有人告诉我关键字不能是表达式。 有没有一种方法可以让关键字成为变量? 谢谢

您可以将关键字参数预构建为字典,然后使用**语法传递。

>>> items = ['a','b','c']
>>> def print_kwargs(**kwargs):
...   for key,value in kwargs.iteritems():
...     print "%s = %s" % (key, value)
...
>>> d = {items[0] : items[1]}
>>> print_kwargs(**d)
a = b

例如:

d = {}
for item in search:
    items = item.split('=')
    d[items[0]] = items[1]
results = results.filter(**d)

暂无
暂无

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

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