zoukankan      html  css  js  c++  java
  • drf 序列化获取商品分类数据

    • 创建一级路由  
    from django.urls import path,include
    # 一级路由
    urlpatterns = [
        
        path('pinmeimei/', include('pinmeimei.urls')),
    ]
    • 创建二级路由
    from django.urls import path
    from . import views
    #二级路由
    urlpatterns = [
        path('category/',views.CategoryView.as_view() ),
        path('goods/',views.GoodsView.as_view() ),
    ]
    • 创建serializers.py 文件方便写序列化
      •   在py文件中写商品分类的序列化
    #商品分类序列化
    class CategorySerializer(serializers.ModelSerializer):
    
        class Meta:
            model = models.Category  #指定表
    
            # fields = '__all__'    #显示所有字段
            fields = ('id','name')  #显示指定字段  可以使用元组或者列表
    • 商品分类类
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from . import models
    from . serializers import *
    
    #商品分类
    class CategoryView(APIView):
        def get(self,request):
            category = models.Category.objects.filter(status=1).all()   #获取商品分类中有效的数据
            cate_date = CategorySerializer(category,many=True)  #对获取到的数据进行序列化,多条数据加上many=True
            print(cate_date)
            if cate_date:  #如果存在获取返回值 status 状态码,msg  返回的提示信息,data 返回的数据根据restful风格
                return Response({
                    'status':200,
                    'msg':'',
                    'data':cate_date.data
                })
            return Response({
                'status':201,
                'msg':'网络连接错误,请稍后重试',
                'data':''
            })
    •  测试

    落后就要吃土,努力吧,骚年!!!
  • 相关阅读:
    最深叶节点的最近公共祖先
    ML-Agents(十)Crawler
    ML-Agents(九)Wall Jump
    ML-Agents(八)PushBlock
    ML-Agents(七)训练指令与训练配置文件
    Unity Editor扩展编辑器中显示脚本属性
    ML-Agents(六)Tennis
    数据结构(二)—栈
    ML-Agents(五)GridWorld
    ML-Agents(四)3DBall补充の引入泛化
  • 原文地址:https://www.cnblogs.com/u-damowang1/p/12131057.html
Copyright © 2011-2022 走看看