第十三单元 混入试图基类 简化后端代码

第十三单元 混入试图基类 简化后端代码,第1张

配置信息
INSTALLED_APPS = [

    'myapp', # 子应用
    'rest_framework', # drf框架
    'corsheaders' # 跨域
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware' # 跨域中间件
]

CORS_ORIGIN_ALLOW_ALL = True  # 允许所有源访问
序列化器代码
from rest_framework import serializers
from myapp.models import Kinds,Goods

class KindSerializers(serializers.ModelSerializer):
    class Meta:
        model = Kinds
        fields = '__all__'

class GoodSerializers(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = '__all__'


# 外键返回的种类名称
class GoodSerializers2(serializers.ModelSerializer):
    kind = serializers.SlugRelatedField(read_only=True,slug_field='kind_name')
    class Meta:
        model = Goods
        fields = '__all__'
视图代码
from django.shortcuts import render
from myapp.serializers import KindSerializers,GoodSerializers,GoodSerializers2
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import Kinds,Goods
# Create your views here.
# 种类 增查
class KindsView(ListCreateAPIView):
    queryset = Kinds.objects.all()
    serializer_class = KindSerializers
# 种类改、删、查一
class KindsView2(RetrieveUpdateDestroyAPIView):
    queryset = Kinds.objects.all()
    serializer_class = KindSerializers
# 商品 增查
class GoodsView(ListCreateAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodSerializers
# 商品改、删、查一
class GoodsView2(RetrieveUpdateDestroyAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodSerializers
# 通过种类id获取商品信息
class GoodsView3(APIView):
    def get(self,request,id):
        try:
            good_data = Goods.objects.filter(kind_id=id)
        except Exception as e:
            print(e)
            return Response({'msg':'error'},status=404)
        ser = GoodSerializers2(good_data,many=True)
        return Response(ser.data,status=200)
路由
from django.urls import path
from myapp import views
urlpatterns = [
    # 种类 增查
    path('kind/',views.KindsView.as_view()),
    # 种类改、删、查一
    path('kind//',views.KindsView2.as_view()),
    # 商品 增查
    path('good/', views.GoodsView.as_view()),
    # # 商品改、删、查一
    path('good//', views.GoodsView2.as_view()),

    path('good2//', views.GoodsView3.as_view()),
]
// 跨域
module.exports = {
    devServer:{
        proxy:'http://127.0.0.1:8000/'
    }
}
// 封装axios请求
import Axios from 'axios'

export function get(url,params){
    return Axios.get(url,params)
}

export function put(url,params){
    return Axios.put(url,params)
}

export function post(url,params){
    return Axios.post(url,params)
}

export function del(url,params){
    return Axios.delete(url,params)
}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/875437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存