Django filter with OR condition using dict argument

前端 未结 3 1059
没有蜡笔的小新
没有蜡笔的小新 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:32

    You can restructure your dictionary into a list of single key-value dictionaries and use unpacking on each dict inside the Q expression like so:

    from functools import reduce
    import operator
    
    from django.db.models import Q
    
    # your dict is my_filter
    q = model.objects.filter(reduce(operator.or_, 
                                    (Q(**d) for d in [dict([i]) for i in my_filter.items()])))
    

    reduce on or_ joins the Q expressions on an OR.

    You could also use a generator expression where you have the list of dicts:

    q = model.objects.filter(reduce(operator.or_, 
                                    (Q(**d) for d in (dict([i]) for i in my_filter.items()))))
    

提交回复
热议问题