简体   繁体   中英

Django Rest Framework Filter not Working, The filter button is not showing on browsable API

Good day I am new with django and django rest framework. I am trying to do some filtering. I followed the steps on the docs https://www.django-rest-framework.org/api-guide/filtering/ but nothing is working, it doesnt even show the filter button on browsable api. hope someone can help. thank you

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_filters',
    'rfproducts',
    'frontend'
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 15,
}

views.py

class ProductsView(generics.ListAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializers
    filterset_fields = ['category']

models.py

class Products(models.Model):
    product_partnumber = models.CharField(max_length=255)
    image_link = models.URLField()
    pdf_link = models.URLField()
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

serializers.py

class ProductsSerializers(serializers.ModelSerializer):

    specifications = ProductSpecificationSerializers(many=True)
    manufacturer_details = ManufacturerSerializers(source='manufacturer', read_only=True)
    category_details = CategorySerializers(source='category', read_only=True)
    
    class Meta:
        model = Products
        fields = ['id', 'product_partnumber', 'image_link', 'pdf_link', 'manufacturer', 'manufacturer_details', 'category', 'category_details', 'subcategory', 'specifications']

    def create(self, request):
        specs_data = request.pop('specifications')
        product = Products.objects.create(**request)
        
        for spec_data in specs_data:
            ProductSpecification.objects.create(product=product, **spec_data)

        return product

when I try to access some parameters in the url like

api/products?category=2

url.py

from django.urls import path, include
from .api import ProductsView, ManufacturerView, SpecificationView, CategoryView, SubcategoryView
from rest_framework import routers

router = routers.DefaultRouter()
router.register('api/products', ProductsView, 'products' )
router.register('api/manufacturers', ManufacturerView, 'manufacturers')
router.register('api/specifications', SpecificationView, 'specification')
router.register('api/category', CategoryView, 'category')
router.register('api/subcategory', SubcategoryView, 'subcategory')

urlpatterns = [
    path('', include(router.urls))
] 

it retruns a blank page with status 200 response. Category field cointains a foreign key.

I am using react for my frontend, does it affect the issue?

In the image the filter button is not showing on the browsable API and also the category value in the url parameters is also existing

sample broswsable api

The filter button is a part of thedjango-crispy-forms module, and is NOT built-in to the django-filter module.

Installation for the django-crispy-forms module:

  1. Run pip install django-crispy-forms
  2. Add 'crispy_forms', to your INSTALLED_APPS in the settings.py file

If installed correctly with proper use of the django-filter module, the "Filters" button should now show up on your browsable API page.

安装 django-crispy-forms 后带有过滤器按钮的可浏览 API 页面

I came into the same question today and it took me a while to make it display. We don't need to install the crispy-forms. The filter button will display when we define the filterset_fields here. Tutorial defines it as filterset_fields = (...) not [...]. But even if I changed my code to ['sku', 'name'] it still works. Reference: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html

 class ProductView(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer pagination_class = StandardResultsSetPagination # filterset_class = [ProductFilter] filterset_fields = ('sku', 'name')
enter image description here enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM