Django Rest framework视图-----APIView

模型类:

# 书籍信息模型
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name='名称')  # 图书名称
    bpub_date = models.DateField(verbose_name='发布日期')  # 发布日期
    bread = models.IntegerField(default=0, verbose_name='阅读量')  # 阅读量
    bcomment = models.IntegerField(default=0, verbose_name='评论量')  # 评论量
    isDelete = models.BooleanField(default=False, verbose_name='逻辑删除')  # 逻辑删除
    logo = models.ImageField(upload_to='booktest', verbose_name='图片', null=True)

    def __str__(self):
        return self.btitle

    # 元类信息 : 修改表名
    class Meta:
        db_table = 'tb_books'
        verbose_name = '图书'
        verbose_name_plural = verbose_name

模型类序列化器:

class BookInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = '__all__'

APIView视图:

from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import BookInfo, HeroInfo
from .serializers import BookInfoSerializer

# GET /books/
class BookListAPIView(APIView):
    def get(self, request):
        # 数据库查询
        queryset = BookInfo.objects.all()

        # todo:手动序列化操作,需要继承django中的view
        # books_list = []
        # for book in queryset:
        #     books_list.append({
        #         'id': book.id,
        #         'btitle': book.btitle,
        #         'bpub_date': book.bpub_date,
        #         'bread': book.bread,
        #         'bcomment': book.bcomment,
        #         'logo': book.logo
        #     })
        # return JsonResponse(books_list)

        # todo:使用序列化器
        # 1.构建序列化器对象,进行序列化操作
        serializer = BookInfoSerializer(queryset, many=True)
        # 2.获取序列化数据
        data = serializer.data
        # 3. 返回
        return Response(data=data)

 

你可能感兴趣的:(Python,DRF)