How to dynamically compose an OR query filter in Django?

后端 未结 14 1347
清歌不尽
清歌不尽 2021-01-22 05:24

From an example you can see a multiple OR query filter:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

For example, this results in:

14条回答
  •  抹茶落季
    2021-01-22 06:14

    In case we want to programmatically set what db field we want to query:

    import operator
    questions = [('question__contains', 'test'), ('question__gt', 23 )]
    q_list = [Q(x) for x in questions]
    Poll.objects.filter(reduce(operator.or_, q_list))
    

提交回复
热议问题