DRF新手-陷入小错误,请协助

时间:2019-07-04 06:33:49

标签: python-3.x django-rest-framework

我创建了1个API,它在所有方面都正常工作。 我创建了第二个API DRF标题,该标题显示了我在做错误操作的旧api的标题。

serializers.py

from rest_framework import serializers
from .models import Brand, Category


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = (
            'id',
            'name',
            'slug',
            'icon',
            'featured_image',
            'url'
        )

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = (
            'id',
            'name',
            'slug',
            'featured_image',
        )

products.url

router = routers.DefaultRouter()
router.register(r'', BrandViewSet)
router.register(r'', CategoryViewSet)

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

product.view

class CategoryViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
    """
    API endpoint that allows sites to be viewed or edited
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

没有错误,但是当我运行API网址时,它显示的是品牌列表而不是类别列表,

enter image description here

1 个答案:

答案 0 :(得分:1)

问题是您已将视图注册到同一端点。因此,它解决了找到的第一个问题。

这样向不同的端点进行注册:

/^[ \t]*$/

因此,您可以通过router = routers.DefaultRouter() router.register(r'brands', BrandViewSet) router.register(r'categories', CategoryViewSet) urlpatterns = [ path('', include(router.urls)), ] 访问品牌,并通过127.0.0.1:8000/brands访问类别