from .models import Publish
class PublishSerializer(serializers.ModelSerializer):
class Meta:
model = Publish
fields = "__all__"
from .models import Author, Publish
from .serializers import AuthorSerializer, PublishSerializer
class PublishView(APIView):
def get(self, request):
publishs = Publish.objects.all() #获取所有数据
serializer = PublishSerializer(instance=publishs, many=True) #构建序列化器
return Response(serializer.data)
def post(self, request):
serizlizer = PublishSerializer(data=request.data) #反序列化器
#数据校验
#验证通过 serializer.data
#验证不通过 serializer.errors
if serizlizer.is_valid():
# Author.objects.create(**serializer.validated_data) 这种原始传入数据的方法
# return Respons("OK")
serizlizer.save()
return Response(serizlizer.data)
else:
return Response(serizlizer.errors)
class PublishDetailView(APIView):
def get(self, request, pk):
publish = Publish.objects.get(pk=pk)
serializer = PublishSerializer(instance=publish,many=False)
return Response(serializer.data)
def put(self, request, pk):
publish = Publish.objects.get(pk=pk)
serializer = PublishSerializer(instance=publish, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
def delete(self, request, pk):
Publish.objects.get(pk=pk).delete()
return Response()
from .views import PublishView, PublishDetailView
urlpatterns = [
path('publish/', PublishView.as_view()),
re_path('publish/(?P\d+)/', PublishDetailView.as_view())
]
get post
http://127.0.0.1:8000/stu/publish
put delete get
http://127.0.0.1:8000/stu/publish/1/