Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filterset_fields with DjangoFilterBackend not working

My class:

class InvoicePeriodViewSet(viewsets.ModelViewSet):
    permission_classes = (
        permissions.AllowAny,
    )
    queryset = models.InvoicePeriod.objects.all()
    serializer_class = serializers.InvoicePeriodSerializer
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    filterset_fields = ('days_interval', )

it's not working at all. I searched in other stack overflow questions and they didn't help me (here, here, here and here).

I have 'django-filter' (django-filter==1.0.4) added to my apps, my django version is (Django==1.11.1) and rest (djangorestframework==3.8.2)

I really don't want to add a filter_class. I have other view with filterclass and it's working but I don't want to make so many filterclasses. It would be perfect that the filterset_fields feature worked. If not I will have to create the filter_class by a function so I won't have to create 30+ of them.

like image 339
Shil Nevado Avatar asked Aug 29 '18 08:08

Shil Nevado


People also ask

How do you use DjangoFilterBackend?

The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters. rest_framework. FilterSet) class for the given fields.

How do I filter Queryset in Django REST framework?

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the . get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.

How do you add search functionality to a Django REST framework powered app?

Set search fields using the query parameter The Django REST framework provides search functionality out of the box. Search can be accomplished by following three steps: Setting search_fields in the class. Setting filter_backends in the class.

What is Queryset in Django REST framework?

Arguments: queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True .


1 Answers

Well, finally I found the problem thanks to validname answer. He suggested to use "filter_fields" I went into django-filter documentation and found that in new version (1.1.0) filter_fields is renamed to filterset_fields, so as I was using django-filter 1.0.4 the filterset_fields didn't exists.

like image 88
Shil Nevado Avatar answered Nov 20 '22 01:11

Shil Nevado