GenericAPIView---get_object含

https://www.bilibili.com/video/BV1z5411D7BQ?p=14&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

https://www.bilibili.com/video/BV1z5411D7BQ?p=15&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

 

views.py    (查询所有、提交)

from sers.models import  Book
from rest_framework import serializers
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

class BookSerializers(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields = "__all__"

class BookView(GenericAPIView):
    # 获取所有书籍---操作数据库
    queryset = Book.objects.all()
    #序列化模型(序列化器)
    serializer_class = BookSerializers

    def get(self,requet):
        # # GenericAPIView提供了get_queryset的方法,获取当前类的queryset变量
        # # GenericAPIView提供了get_serializer_class的方法,获取当前类的serializer_class变量
        # serializer=self.get_serializer_class()(instance=self.get_queryset(), many=True)
        #但是上面这么写太丑了
        # GenericAPIView提供了get_serializer的方法,做了上面2行代码做的逻辑
        serializer=self.get_serializer(instance=self.get_queryset(), many=True)

        # # # # 调用序列化对象的data获取序列化后的数据
        data = serializer.data
        return Response(data)
        
        
     def post(self, request):
        # 老写法
        # 获取请求的数据 #request.data可以拿到表单或json的数据
        # print("data",request.data)
        # 构建序列化器
        # serializer = BookSerializers(data=request.data)
        #新写法
        serializer = self.get_serializer(data=request.data)
        # # 校验数据--返回boolen值,成功信息放到serializer.validated_data,错误信息放到serializer.errors
        if serializer.is_valid():
            # 数据插入到数据库中
            # save()写法插入数据-----------
            serializer.save()
            #数据校验通过
            return Response(f'校验成功信息:{serializer.validated_data}') #serializer.validated_data是反序列化成数据模型了
            # return Response(f'校验成功信息:{serializer.data}') #"校验成功信息:{'title': 'j11', 'price': 1999, 'date': '2020-12-12 00:00:00'}"
        else:
            # 数据校验失败
            return Response(f'校验失败信息:{serializer.errors}')

 

models.py

from django.db import models

# Create your models here.
class Book(models.Model):
    title=models.CharField(max_length=55,verbose_name="书籍名称")
    price=models.IntegerField(verbose_name="价格")
    # pub_date=models.DateField(verbose_name="出版日期")
    pub_date = models.CharField(max_length=55,verbose_name="出版日期")

 

 

view.py (查询单个、更新、删除)

class BookSerializers(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields = "__all__"

class BooketailView(GenericAPIView):
    # 获取所有书籍---操作数据库
    queryset = Book.objects.all()
    #序列化模型(序列化器)
    serializer_class = BookSerializers

    # 带参数id查询
    def get(self, request, pk):
        # get_object要配合url的有名分组参数,默认是pk值,在self.get_queryset的基础下进行id的过滤
        serializer=self.get_serializer(instance=self.get_object())
        return Response(serializer.data)

    def put(self, request, pk):
        # 构建序列化器对象 # instance放原来的信息,data放要修改成的信息
        serializer = self.get_serializer(instance=self.get_object(),data=request.data, many=False)
        if serializer.is_valid():
            # 更新操作
            serializer.save()
            return Response(f"更新成功{serializer.data}")
        else:
            return Response(f"更新失败: {serializer.errors}")

    def delete(self,request,pk):
        self.get_object().delete()
        return Response("删除成功")

 

posted @ 2022-10-23 13:58  凯宾斯基  阅读(45)  评论(0编辑  收藏  举报