【问题标题】:Arbitrary number of search terms任意数量的搜索词
【发布时间】:2013-07-10 13:48:12
【问题描述】:

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

我的想法是,该 url 将具有类似于以下内容的模式:/[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])

很遗憾,有人告诉我关键字不能是表达式。有没有办法让关键字成为变量?谢谢

【问题讨论】:

标签: python regex django filter


【解决方案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)

【讨论】:

  • 太棒了!谢谢。还有一个问题。如果我需要基于对象中包含的对象中的属性进行过滤(也就是说,我有对象 A,它具有对对象 B 的外键引用,并且我需要根据对象 B 持有的属性进行过滤) 我该怎么做?如果我不需要使用kwarg,那会比较简单,只需results.filter(B__property=value)。我怎么能用字典做到这一点?
  • @dar2162 我会以我不了解 Django 的事实作为开头,但如果它真的只是 B__property=value,那么只需将该键值对添加到字典中,如 d[B__property]=value 之前将其传递给过滤器。这个字典可以包含任何你想当作关键字参数的键值对。
  • 太棒了!虽然,它需要是一个连接字符串,即property='B__%s' %items[0] 然后d[property]=items[1]
猜你喜欢
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多