本文共 1654 字,大约阅读时间需要 5 分钟。
goods.views.py
from rest_framework import mixinsfrom rest_framework import viewsetsfrom .models import Goods,GoodsCategoryfrom .serializer import GoodsSerialize,GoodsCategorySerializeclass 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,includefrom rest_framework.routers import DefaultRouterfrom .views import GoodsListViewSet,GoodsCategoryViewSetrouter = DefaultRouter()router.register(r'category',GoodsCategoryViewSet,base_name='category')urlpatterns = [ path('',include(router.urls))]
goods.serializer.py
from rest_framework import serializersfrom .models import Goods,GoodsCategoryclass 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,即使用全部字段
转载地址:http://vrnvb.baihongyu.com/