How to dynamically compose an OR query filter in Django?

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

    You could chain your queries as follows:

    values = [1,2,3]
    
    # Turn list of values into list of Q objects
    queries = [Q(pk=value) for value in values]
    
    # Take one Q object from the list
    query = queries.pop()
    
    # Or the Q object with the ones remaining in the list
    for item in queries:
        query |= item
    
    # Query the model
    Article.objects.filter(query)
    

提交回复
热议问题