首页 > 其他分享 >GenericAPIView

GenericAPIView

时间:2022-10-23 14:14:02浏览次数:43  
标签:GenericAPIView get models queryset class serializer

https://www.bilibili.com/video/BV1z5411D7BQ?p=14&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_class的方法,做了上面2行代码做的逻辑
        serializer=self.get_serializer(instance=self.get_queryset(), many=True)

        # # # # 调用序列化对象的data获取序列化后的数据
        data = serializer.data
        return Response(data)

 

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="出版日期")

 

标签:GenericAPIView,get,models,queryset,class,serializer
From: https://www.cnblogs.com/kaibindirver/p/16818468.html

相关文章