Django: OR queries with dynamic field names

空扰寡人 提交于 2019-12-19 09:45:47

问题


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:


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)



来源:https://stackoverflow.com/questions/10340106/django-or-queries-with-dynamic-field-names

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