Django: OR queries with dynamic field names

2019-02-18 20:09发布

I have a value and want to get all instances having the value in one or more column. And to make this a bit more complex, the field list is dynamic.

So, what I have is: ['field1', 'field2', 'field3', ...]

What I need is: Q(field1='value') | Q(field2='value') | Q(field3='value') | ...

How can I get this?

1条回答
霸刀☆藐视天下
2楼-- · 2019-02-18 20:46

Use ** dictionary-to-kw-args expansion:

q = Q()
for field in fields:
    q = q | Q(**{field: "value"})

(as Q() yield a Q which "does nothing", as far as I can tell)

查看更多
登录 后发表回答