How to dynamically compose an OR query filter in Django?

后端 未结 14 1364
清歌不尽
清歌不尽 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:16

    Solution which use reduce and or_ operators to filter by multiply fields.

    from functools import reduce
    from operator import or_
    from django.db.models import Q
    
    filters = {'field1': [1, 2], 'field2': ['value', 'other_value']}
    
    qs = Article.objects.filter(
       reduce(or_, (Q(**{f'{k}__in': v}) for k, v in filters.items()))
    )
    

    p.s. f is a new format strings literal. It was introduced in python 3.6

提交回复
热议问题