chapter 6

6.2 category 后台url配置

goods.views.py




from rest_framework import mixins
from rest_framework import viewsets

from .models import Goods,GoodsCategory
from .serializer import GoodsSerialize,GoodsCategorySerialize



class GoodsCategoryViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    '''
    url:goods/category/
    GoodsCategory views
    商品分类页表
    '''
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategorySerialize

goods.urls.py

from django.urls import path,re_path,include
from rest_framework.routers import DefaultRouter

from .views import GoodsListViewSet,GoodsCategoryViewSet

router = DefaultRouter()
router.register(r'category',GoodsCategoryViewSet,base_name='category')

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

goods.serializer.py

from rest_framework import serializers
from .models import Goods,GoodsCategory




class GoodsCategorySerialize3(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"#和forms.py 的功能一样,但是serializer可以不指明字段,直接写all,即使用全部字段


class GoodsCategorySerialize2(serializers.ModelSerializer):
    '''
    arent_category = models.ForeignKey('self', verbose_name='父类目录级'related_name='sub_cat')
    sub_cat 是在modes.py中GoodsCategory中定义字段时就定义好了的
    '''
    sub_cat = GoodsCategorySerialize3(many=True)#
    class Meta:
        model = GoodsCategory
        fields = "__all__"#和forms.py 的功能一样,但是serializer可以不指明字段,直接写all,即使用全部字段


class GoodsCategorySerialize(serializers.ModelSerializer):
    sub_cat = GoodsCategorySerialize2(many=True)
    class Meta:
        model = GoodsCategory
        fields = "__all__"#和forms.py 的功能一样,但是serializer可以不指明字段,直接写all,即使用全部字段


猜你喜欢

转载自blog.csdn.net/bobbykey/article/details/81252481