Django filter using **kwargs

I'm trying to filter using some fields in an array like:

qs = Model.objects.all()
fields_list = ['a', 'b', 'c']

for field in fields_list:
    filter = {field: 20}
    qs.filter(**filter)

return qs

This piece of code, works in shell but not in runtime. What am I doing wrong?

1 answer

  • answered 2018-04-14 15:45 dirkgroten

    try:

    filter = {}
    for field in fields_list:
        filter.update({field: 20})
    qs = qs.filter(**filter)
    return qs