1.路由配置:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^PublishView/', views.PublishView.as_view()),
url(r'^PublishDetailView/(?P\d+)', views.PublishDetailView.as_view()),
]
2.视图类配置:
# views.py
from django.shortcuts import render
from rest_framework.views import APIView
from app01 import models
from app01.MySer import BookSer,PublishSer,AuthorSer
from rest_framework.response import Response
# Create your views here.
class PublishView(APIView):
def get(self,request):
publish_list = models.Publish.objects.all()
bs = PublishSer(publish_list, many=True)
return Response(bs.data)
def post(self, request):
bs = PublishSer(data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors)
class PublishDetailView(APIView):
def get(self, request, pk):
publish_obj = models.Publish.objects.filter(pk=pk).first()
bs = PublishSer(publish_obj, many=False)
return Response(bs.data)
def put(self, request, pk):
publish_obj = models.Publish.objects.filter(pk=pk).first()
bs = PublishSer(data=request.data, instance=publish_obj)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.data)
def delete(self, request, pk):
models.Publish.objects.filter(pk=pk).delete()
return Response("")
3.新建的表序列化类
# MySer.py
from rest_framework import serializers
from app01 import models
class BookSer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'
class PublishSer(serializers.ModelSerializer):
class Meta:
model = models.Publish
fields = '__all__'
class AuthorSer(serializers.ModelSerializer):
class Meta:
model = models.Author
fields = '__all__'