[Answered ]-Dynamic filter addtion with icontains

1👍

You can build a dict and then unpack it through standard python double asterisks (This answer talks a bit more about the unpacking of dicts).

params = {
    '{}__icontains'.format(field): search,
}
qs = qs.filter(**params)

This way is specially useful if you want to conditionally add many filter values and unpack them only once in the .filter() statement.

qs = self.get_queryset()
filter_params = {}

for field_name in ['field_1', 'field_2']:
    field_value = req_serializer.validated_data[field_name]

    if field_value:
        k = '{}__icontains'.format(field_name)
        filter_params[k] = field_value   # adds a new key to the dict

if len(filter_params) > 0:
    qs = qs.filter(**filter_params)
👤Ralf

Leave a comment