APIView单一资源的查看更新删除

APIView单一资源的查看更新删除

一、构建路由
re_path("author/(/d+)",AuthorDetailView.as_view)),
二、视图类
在views.py中添加AuthorDetailView类

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
四、代码测试,用浏览器或者Postman


    API : http://127.0.0.1:8000/stu/author/2/ 

你可能感兴趣的:(python,开发语言,APIView,rest_framework)