Trying to reduce Django Q objects with operator.or_ seems to result in reduction with 'AND'

不羁岁月 提交于 2019-12-23 03:00:14

问题


I am working on an application in Python/Django. I am trying to make a filter by reducing a list of Q objects with Python's operator.or_ function. Unfortunately it results in a list that is combined with an AND rather than operator.or_. The problem occurs in the following code:

print 'operator.or_', operator.or_
filter = reduce(operator.or_, q_objects[key])
print key, '->', filter

The statement

print 'operator.or_', operator.or_

results in

operator.or_ <built-in function or_>

so that seems succesful. However,

filter = reduce(operator.or_, q_objects[key])
print key, '->', filter    

results in (with added formatting)

some_key -> (
        AND: 
        ('some_field__icontains', u'search string 1'), 
        ('other_field__icontains', u'search string 2')
    )

As you can see, the result has an AND rather than an OR. Can anyone see what I am doing wrong?

Regarding q_objects[key], it is created as follows:

q_dict = {'some_field__icontains': u'search string 1', 'other_field__icontains': u'search string 2'}
q_objects[key] = [Q(**q_dict)]

回答1:


q_objects[type] = [Q(**q_dict)]

No. You need to handle each element separately.

q_objects[type] = [Q(**{k: v}) for (k, v) in q_dict.iteritems()]


来源:https://stackoverflow.com/questions/8138919/trying-to-reduce-django-q-objects-with-operator-or-seems-to-result-in-reduction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!