re_path("author/(/d+)",AuthorDetailView.as_view)),
class AuthorDetailView(APIView):
def get(self, request, pk):
author = Author.objects.get(pk=pk)
serializer = AuthorSerializer(instance=author,many=False)
return Response(serializer.data)
def put(self, request, pk):
author = Author.objects.get(pk=pk)
serializer = AuthorSerializer(instance=author, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
def delete(self, request, pk):
Author.objects.get(pk=pk).delete
return Response()
三、修改序列化器类
在serializers.py中添加update方法
class AuthorSerializer(serializers.Serializer):
name = serializers.CharField(max_length=32)
age = serializers.IntegerField()
def create(self,validated_data):
author_obj = Author.objects.create(**validated_data)
return author_obj
def update(self, instance, validated_data):
Author.objects.filter(pk=instance.pk).update(**validated_data)
return instance
API : http://127.0.0.1:8000/stu/author/2/