首页 > 解决方案 > Django Rest Framework 过滤器不起作用,过滤器按钮未显示在可浏览的 API 上

问题描述

美好的一天,我是 django 和 django rest 框架的新手。我正在尝试进行一些过滤。我按照文档https://www.django-rest-framework.org/api-guide/filtering/上的步骤进行操作,但没有任何效果,它甚至没有在可浏览的 api 上显示过滤器按钮。希望有人可以提供帮助。谢谢你

设置.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,
}

视图.py

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

模型.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)

序列化程序.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

当我尝试访问 url 中的一些参数时

api/products?category=2

网址.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))
] 

它重新运行一个带有状态 200 响应的空白页。类别字段包含一个外键。

我正在为我的前端使用 react,它会影响问题吗?

在图像中,过滤器按钮未显示在可浏览的 API 上,并且 url 参数中的类别值也存在

可浏览的 api 示例

标签: djangodjango-rest-frameworkdjango-filterdjango-filters

解决方案


推荐阅读