pass all fields of model in django filter backend

3.8k views Asked by At

is there any way in which we can pass all the fields of a model to django filter backend without explicitly passing the names of fields in search_fields and filter_fields

i have made a generic viewset which serializes all the fields of the model passed to it, but i am facing problem in applying generic filters to it

for eg,

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('username', 'email')

in the above code, we have explicitly passed search_fields but in my code, i can't pass the fields explicitely as everytime different model may be passed.

2

There are 2 answers

0
yedpodtrzitko On BEST ANSWER

I dont think it's wise to do it, as some fields can reveal sensitive information, but you can try to pass all fields from the model:

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = [f.name for f in User._meta.get_fields()]

Here are the docs for using get_fields:

Options.get_fields(include_parents=True, include_hidden=False)[source]

Returns a tuple of fields associated with a model. get_fields() accepts two parameters that can be used to control which fields are returned:

  • include_parents True by default. Recursively includes fields defined on parent classes. If set to False, get_fields() will only search for fields declared directly on the current model. Fields from models that directly inherit from abstract models or proxy classes are considered to be local, not on the parent.
  • include_hidden False by default. If set to True, get_fields() will include fields that are used to back other field’s functionality. This will also include any fields that have a related_name (such as ManyToManyField, or ForeignKey) that start with a “+”.
0
Wilfried On

https://docs.djangoproject.com/en/1.10/ref/models/meta/

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = [field.name for field in User._meta.fields]