Django_filters filter option not visible on browsable api

368 views
Skip to first unread message

Shekhar Nunia

unread,
Sep 27, 2023, 4:19:34 AM9/27/23
to Django REST framework
Hi,


REST_FRAMEWORK = {
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
}


class ProductListAPIView(generics.ListAPIView):
    serializer_class = ProductSerializer
    filterset_class = ProductFilter

    def get_queryset(self):
        return ProductService().get_products()

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        return send_response(
            data=response.data,
            status_code=response.status_code,
            message=ResponseMessages.DATA_FETCH_SUCCESS,
        )

class ProductFilter(django_filters.FilterSet):
    price_min = django_filters.NumberFilter(field_name="price", lookup_expr="gte")
    price_max = django_filters.NumberFilter(field_name="price", lookup_expr="lte")

    class Meta:
        model = Product
        fields = [
            "brand",
            "product_name",
            "lens_category",
            "price_min",
            "price_max",
        ]

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.postgres",
    "rest_framework",
    "products",
    "crispy_forms",
    "django_filters",
    "drf_yasg",
]

Django==4.2.4
django-crispy-forms==2.0
django-filter==23.2
djangorestframework==3.14.0

I tried to setup another basic new project with 1 model and in that case I was able to see filter button 
Screenshot 2023-09-27 134800.png

but this didn't work on my main project, can anyone help me understand what I missed on the above code snippet so that the filter not showing on browsable API even tho it's showing on swagger with all options.

I hope to get some help regarding this.

Thanks

: Anthony: Crawford.

unread,
Nov 20, 2023, 8:08:14 PM11/20/23
to Django REST framework
I have not created a filterset before but I use this code in my API views, and I am always able to filter in browsable API.

filter_backends = [DjangoFilterBackend]
filterset_fields = ['x', 'y', 'z']

And in settings.py:

REST_FRAMEWORK = {
...
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
...

: Anthony: Crawford.

unread,
Nov 20, 2023, 8:11:22 PM11/20/23
to Django REST framework
... and these imports in your views.py:

from rest_framework import generics
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

On Wednesday, September 27, 2023 at 5:19:34 AM UTC-3 shekha...@gmail.com wrote:
Reply all
Reply to author
Forward
0 new messages