Django:如何在Q()语句中使用字符串作为关键字?

时间:2011-11-15 23:22:52

标签: python django django-queryset

我正在为某个模型编写一个简单的搜索表单。让我们调用模型Orchard并为其提供属性applesorangespears,只是为了演示。

因此,表单不需要填写所有字段。因此,您可以搜索applesoranges,但不能搜索。我需要像这样过滤:

Orchard.objects.filter(apples=request.GET.get('apples'), oranges=request.GET.get('oranges'), pears=request.GET.get('pears'))

但如果pears为空,则不会返回任何结果。

我的第一个想法是使用Q个对象,如下所示:

from django.db.models import Q

options = {}
options['apples'] = request.GET.get('apples')
options['oranges'] = request.GET.get('oranges')
options['pears'] = request.GET.get('pears')

queries = None

for key in options:
    if options[key] != u'':
        if queries:
            queries &= Q(key=options[key]) # <=== problem here
        else:
            queries = Q(key=options[key])  # <=== same problem here

results = Orchard.objects.filter(queries)

问题出现在那些标记的行中。我显然不能只使用“key”作为属性关键字,因为它不需要字符串,它基本上需要一个变量。

那么......我该如何解决这个问题?

除非这个问题的已知解决方案不涉及Q。这也会有所帮助。

2 个答案:

答案 0 :(得分:12)

这是使用变量作为关键字arg中的键的一般问题。解决方案是将事物包装在dict中并解压缩它:

queries &= Q(**{key: options[key]})

或在你的情况下

for option in options:
    if options[option] is None:
        del(options[option])
# or otherwise only add the ones you actually want to filter on
# then
results = Orchard.objects.filter(**options)

答案 1 :(得分:0)

@ second的答案是正确的,用**运算符解压缩字典以提供关键字参数。

但是,如果您只使用 AND 来组合Q个对象而不是 OR ,那么您实际上并不需要使用{{1}示例中的对象。只需构建一个查找字典,然后将其用作Q的关键字参数。

filter