配置信息
INSTALLED_APPS = [
'myapp',
'rest_framework',
'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
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
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/<int:pk>/',views.KindsView2.as_view()),
path('good/', views.GoodsView.as_view()),
path('good/<int:pk>/', views.GoodsView2.as_view()),
path('good2/<int:id>/', 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)
}