Home > Mobile >  Django: name 'filter_name__icontains' is not defined
Django: name 'filter_name__icontains' is not defined

Time:06-15

I am working on custom filter in my Django (DRF) app.

Basic filtering (iexact) is working:

queryset = queryset.filter(**{filter_name: term.get(filter_name)}) # OK

But I want to filter CharFields with icontains logic:

queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)}) # ERROR

Error text

NameError: name 'filter_name__icontains' is not defined

Question: how can I support icontains filtering in my function?

My code

from django.db.models import QuerySet, CharField
from rest_framework.filters import BaseFilterBackend
from rest_framework.request import Request


    class AbstractFilterBackend(BaseFilterBackend):
        @staticmethod
        def __execute_default_filters(queryset, terms: list):
            for term in terms:
                filter_name = next(iter(term.keys()))
    
                if hasattr(queryset.model, filter_name):
                    if queryset.model._meta.get_field(filter_name).__class__ is CharField:
                        queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)})
                    else:
                        queryset = queryset.filter(**{filter_name: term.get(filter_name)})
    
            return queryset

CodePudding user response:

While filter_name is a variable, you did not define filter_name__icontains. You can use string formatting for this:

queryset = queryset.filter(**{f'{filter_name}__icontains': term.get(filter_name)})
  • Related