How to dynamically compose an OR query filter in Django?

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

    To build more complex queries there is also the option to use built in Q() object's constants Q.OR and Q.AND together with the add() method like so:

    list = [1, 2, 3]
    # it gets a bit more complicated if we want to dynamically build
    # OR queries with dynamic/unknown db field keys, let's say with a list
    # of db fields that can change like the following
    # list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3']
    
    # init our q objects variable to use .add() on it
    q_objects = Q(id__in=[])
    
    # loop trough the list and create an OR condition for each item
    for item in list:
        q_objects.add(Q(pk=item), Q.OR)
        # for our list_with_strings we can do the following
        # q_objects.add(Q(**{item: 1}), Q.OR)
    
    queryset = Article.objects.filter(q_objects)
    
    # sometimes the following is helpful for debugging (returns the SQL statement)
    # print queryset.query
    

提交回复
热议问题