How to dynamically compose an OR query filter in Django?

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

    A shorter way of writing Dave Webb's answer using python's reduce function:

    # For Python 3 only
    from functools import reduce
    
    values = [1,2,3]
    
    # Turn list of values into one big Q objects  
    query = reduce(lambda q,value: q|Q(pk=value), values, Q())  
    
    # Query the model  
    Article.objects.filter(query)  
    

提交回复
热议问题