Django Rest Framework以及序列化(1)

特性
可浏览API
提供丰富认证
⽀持数据序列化
可以轻量嵌⼊,仅使⽤fbv
强⼤的社区⽀持
官方网站:https://www.django-rest-framework.org/
中文翻译网站:https://q1mi.github.io/Django-REST-framework-documentation/

环境的安装和配置
DRF依赖于:
Python (3.5, 3.6, 3.7, 3.8)
Django (1.11, 2.0, 2.1, 2.2, 3.0)

安装djangorestframework

pip install djangorestframework

添加rest_framework应⽤
在settings.py的INSTALLED_APPS中加’rest_framework’

INSTALLED_APPS = [
 ...
 'rest_framework',
]

models中创建models模型

app中创建序列化文件serializers.py
继承关系:基本继承类(APIView)
#关联对象 : 模型必须有外键关系
关联只返回主键
# heros = serializers.PrimaryKeyRelatedField(many=True,read_only=True)
关联返回字符串信息
# heros = serializers.StringRelatedField(many=True,read_only=True)
关联返回序列化
heros = HeroInfoSerializer(many=True,read_only=True)

通过check_字段名添加字段判断

from rest_framework import serializers
from rest_framework.renderers import JSONRenderer

方法一:
# class BookInfoSerializer(serializers.Serializer):
#     id = serializers.IntegerField()
#     btitle = serializers.CharField(min_length=3)
#     bpub_date = serializers.DateField(required=False)
#     bread = serializers.IntegerField(required=False)
#     bcomment = serializers.IntegerField(required=False)
#     bimage = serializers.CharField(max_length=300,required=False)
from App.models import BookInfo

建议使用以下方法序列化
方法二
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = '__all__' #('id','btitle','bpub_date','bread','bcomment','bimage')



def check_bcomment(value):
    value = int(value)
    if value < 0:
        raise serializers.ValidationError("评论数不能小于0")

class BookInfoSerializers(serializers.ModelSerializer):
    # 关联对象 : 模型必须有外键关系
    关联只返回主键
    # heros = serializers.PrimaryKeyRelatedField(many=True,read_only=True)
   关联返回字符串信息
    # heros = serializers.StringRelatedField(many=True,read_only=True)
   关联返回序列化
    heros = HeroInfoSerializer(many=True,read_only=True)
    class Meta:
        model = BookInfo
        # 显示指定使用那些模型中字段
        # fields = ('btitle','bpub_date','bread','bcomment','bimage')

        # 使用模型的全部字段
        fields = "__all__"
        extra_kwargs = {
            'bcomment':{'validators':[check_bcomment]}
        }

    def validate_bread(self,value):
        value = int(value)
        print(value)
        if value < 0:
            raise serializers.ValidationError("阅读数不能小于0")
        return value

操作
序列化(get请求)

class BookInfoView(APIView):
    def get(self,request,bid):
        # bid = kwargs.get('id')
        # 1.查询数据库
        book = BookInfo.objects.filter(pk=bid).first()
        print(book)
        if book:
            # 2.序列化
            serializer = BookInfoSerializer(book)
            print(serializer.data)
            # 3.返回json字符串
            return Response(serializer.data)
        else:
            return Response({'code':0,'msg':'你查询的图书不存在'})


class BooksView(APIView):
    def get(self,request):
        books = BookInfo.objects.all()
        print(books)
        # 如果序列化的对象是查询结果集,则需要使用many=true
        serializer = BookInfoSerializer(books,many=True)
        print(serializer.data)
        return Response(serializer.data)

反向序列化(post,put,patch请求)
serializer = BookInfoSerializers(data=request.data)

class IndexView(APIView):
    def get(self,request,*args,**kwargs):
        books = BookInfo.objects.all()
        # 序列化
        # 如果books是一个模型对象,则many不能设置为True
        # 如果books是一个查询结果集,必须把many设置为True
        print(books)
        serializer = BookInfoSerializers(instance=books,many=True)
        # 获取序列化的结果,会把转换为字典,把结果集转为列表
        print(serializer.data)
        res = Response(serializer.data)
        print(res,type(res))
        return res

    # 新增书籍
    def post(self,request,*args,**kwargs):
        print(request.data)
        # 反向序列化器 给data赋值
        serializer = BookInfoSerializers(data=request.data)
        # 查看验证是否通过
        if serializer.is_valid():
            # 获取验证后数据
            # print(serializer.validated_data)
            book = serializer.save()  # 保存到数据
            return Response({'code':1,'msg':'新增加成功','id':book.id})
        else:
            # 获取验证失败原因
            print(serializer.errors)
            return Response({'code':-1,'msg':serializer.errors})
    # 更新对象
    def put(self,request,bid):
        print(bid)
        # 查询记录
        book = BookInfo.objects.get(pk=bid)
        print(book)
        # 更新数据: 模型对象赋值instance,更新数据赋给data
        serializer = BookInfoSerializers(instance=book,data=request.data)
        if serializer.is_valid():
            res = serializer.save()  # 调用update
            return Response({"code":2,'msg':'更新成功'})
        else:
            return Response({'code':-1,"msg":serializer.errors})

延伸简单的增删改查继承

# 图书列表
class BooksView(ListAPIView):
    # 指定查询结果集
    queryset = BookInfo.objects.all()
    # 指定序列化器
    serializer_class = BookInfoSerializers

# 创建图书
class BooksView2(CreateAPIView):
    serializer_class = BookInfoSerializers

# 更新书籍信息
class BooksView3(UpdateAPIView):
    queryset = BookInfo.objects.all()
    # url中主键的名称
    lookup_url_kwarg = 'bid'
    # 数据库中查询的主键名称
    lookup_field = 'id'
    serializer_class = BookInfoSerializers

# 删除书籍
class BooksView4(DestroyAPIView):
    queryset = BookInfo.objects.all()
    # url中主键的名称
    lookup_url_kwarg = 'bid'
    # 数据库中查询的主键名称
    lookup_field = 'id'
    serializer_class = BookInfoSerializers

查询
class BooksView5(ListAPIView,RetrieveAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializers
    # url中主键的名称
    lookup_url_kwarg = 'bid'
    # 数据库中查询的主键名称
    lookup_field = 'id'

    def get(self,request,*args,**kwargs):
        if len(kwargs) > 0:
            return self.retrieve(request,*args,**kwargs)
        else:
            return self.list(request,*args,**kwargs)

你可能感兴趣的:(django,django,python)