简体   繁体   中英

Generate a django queryset based on dict keys

I have a dict like:

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

And I need a queryset like

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

Thanks

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

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM