Django filter with OR condition using dict argument

前端 未结 3 1049
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 05:50

I have a function on my Django app where I perform some Queryset actions and set it\'s result to Memcache. Since it is a function it has to be of general usage. So in order

3条回答
  •  一生所求
    2020-12-09 06:27

    You can use the bitwise | operator.

    my_filter = Q()
    
    # Or the Q object with the ones remaining in the list
    my_or_filters = {'some_field__gte':3.5, 'another_field':'Dick Perch'}
    
    for item in my_or_filters:
        my_filter |= Q(**{item:my_or_filters[item]})
    
    model.objects.filter(my_filter)
    # unpacks to model.objects.filter(Q(some_field__gte=3.5) | Q(another_field='Dick Perch'))
    

    With this in mind, you may want to load all your queries stored in my_filter into Q objects. Then, you could join all non-OR queries via the same method above w/ the bitwise &: my_filter &= ...

提交回复
热议问题