Trying to reduce Django Q objects with operator.or

2019-06-02 09:52发布

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条回答
你好瞎i
2楼-- · 2019-06-02 10:25
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()]
查看更多
登录 后发表回答