一:获取SPU列表数据:
<一>: 分析:获取列表信息是序列化过程,首先新建序列化器。
1:对比前端传入和模型类,构造序列化器:(最简单的处理方式是先将前端需要的字段,全部注册到fields中,然后再一一和模型类字段进行对比,看看哪个字段需要自己定义)
from rest_framework import serializers
from apps.goods.models import SPU
class SPUModelSerializer(serializers.ModelSerializer):
brand = serializers.StringRelatedField() # 前端需要名字
brand_id = serializers.IntegerField() # 默认是read_only = True : 只参与序列化,现在两个都参与
category1_id = serializers.IntegerField()# 默认是read_only = True : 只参与序列化,现在两个都参与
category2_id = serializers.IntegerField()
category3_id = serializers.IntegerField()
class Meta:
model = SPU
fields = ['id', 'name', 'brand', 'brand_id', 'category1_id', 'category2_id', 'category3_id', 'sales', 'comments', 'desc_detail', 'desc_pack', 'desc_service']
2:创建视图:需要根据keyword过滤:
from rest_framework.viewsets import ModelViewSet
from apps.meiduo_admin.serializers.spu_serializers import *
from apps.goods.models import SPU
from apps.meiduo_admin.paginations import *
class SPUView(ModelViewSet):
queryset = SPU.objects.all().order_by()
serializer_class = SPUModelSerializer
pagination_class = MyPage
def get_queryset(self):
keyword = self.request.query_params.get("keyword")
if keyword:
return self.queryset.filter(name__contains=keyword)
return self.queryset.all()
re_path(r'^goods/$', SPUView.as_view({'get': 'list'})),
3:测试:显示出数据说明成功:
二: 新增SPU可选的品牌:
1:针对品牌表brand建立序列化器:(序列化过程)
新建编辑apps/meiduo_admin/serializers/spu_serializers.py
class BrandSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields =["id", "name"]
2:定义视图和路由:
新建编辑apps/meiduo_admin/views/spu_views.py
# 序列化返回品牌信息
class BrandSimpleView(ListAPIView):
queryset = Brand.objects.all()
serializer_class = BrandSimpleSerializer
re_path(r'^goods/brands/simple/$', BrandSimpleView.as_view()),
3:测试:
三:新增SPU的可选分类:
1:针对商品分类表建立序列化器:
新建编辑apps/meiduo_admin/serializers/spu_serializers.py
class SPUCateSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = GoodsCategory
fields = ["id", "name"]
2:视图和路由:
# 商品可选分类表:
class SPUCateSimpleView(ListAPIView):
queryset = GoodsCategory.objects.all()
serializer_class = SPUCateSimpleSerializer
def get_queryset(self):
parent_id = self.kwargs.get("pk")
# 此时表示是二级或者三级分类
if parent_id:
return self.queryset.filter(parent_id = parent_id)
# 此时表示一级分类
else:
return self.queryset.filter(parent_id = None)
路由:
re_path(r'^goods/channel/categories/$', SPUCateSimpleView.as_view()),
# 新增SPU可选二级或三级份额里
re_path(r'^goods/channel/categories/(?P<pk>\d+)/$', SPUCateSimpleView.as_view()),
3:测试:
四:新增,删除,更新SUP商品:
re_path(r'^goods/$', SPUView.as_view({'get': 'list', 'post': 'create'})),
re_path(r'^goods/(?P<pk>\d+)/$', SPUView.as_view({'get': 'retrieve','put': 'update','delete': 'destroy'})),
测试:一:新增:
二:修改:
三:删除: