6-2 商品类别数据接口
goods/views.py
class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
RetrieveModelMixin 参数可以使得前端输入http://127.0.0.1:8000/categorys/1/而显示id为1的商品,相当于restful接口的GET操作 GET /zoos/ID:获取某个指定动物园的信息
list:
商品分类列表
"""
queryset = GoodsCategory.objects.all()
serializer_class = CategorySerializer
goods/serializers.py
from goods.models import Goods,GoodsCategory
class CategorySerializer3(serializers.ModelSerializer):
class Meta:
model = GoodsCategory
fields = "__all__"
class CategorySerializer2(serializers.ModelSerializer):
sub_cat = CategorySerializer3(many=True) # 在前端的2及类目包含3级类目
class Meta:
model = GoodsCategory
fields = "__all__"
class CategorySerializer(serializers.ModelSerializer):
# 因为商品类别中有三级,GoodsCategory类以自身作为外键,一级是二级的外键,二级是三级的外键
# 可以用如下方式在前段显示外键
sub_cat = CategorySerializer2(many=True) # 注:sub_cat与model中GoodsCategory中的related_name一样
class Meta:
model = GoodsCategory
fields = "__all__"
主url中配置
# 配置category的url
router.register(r'categorys', CategoryViewSet, base_name='categorys')
这样在前端就只显示1的商品
6-3 vue展示商品分类数据
在前端页面的导航栏中显示信息,需要先把host主机名配置
因为django启动的是8000端口,而cnpm启动的是8080端口,涉及到跨域问题,可以前端解决,这里用django后端方式解决。安装https://github.com/ottoyiu/django-cors-headers 这个包,然后再settings中配置:INSTALLED_APPS中添加‘corsheaders’;MIDDLEWARE中添加‘corsheaders.middleware.CorsMiddleware’;再添加CORS_ORIGIN_ALLOW_ALL = True。这样前端就显示出数据。
以上在vue的大致实现流程如下
然后使用vue的for循环取出数据
接下来在xadmin中添加数据显示到导航栏(因为在vue中有item.is_tab为true才会显示,所以在xadmin中要把是否需要导航的√打上)
这样在前端就显示了