Generate a django queryset based on dict keys

2019-03-22 05:48发布

问题:

I have a dict like:

{
    'key1' : val1,
    'key2' : val2
}

And I need a queryset like

Q(key1__icontains = val1) | Q(key2__icontains = val2)

Thanks

回答1:

reduce(operator.or_, Q(**{key + '__icontains': val}) for (key, val) in D.iteritems())


回答2:

There's a more pragmatic approach, as I need to generate various keys from one.

query = None
for key, value in d.iteritems():
    if query is None:
        query = Q(**{key + "__icontains" : value})
    else:
        query |= Q(**{key + "__icontains" : value})