Java教程

serializers的序列化和效验

本文主要是介绍serializers的序列化和效验,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

view中的代码

class Books(APIView):
    def get(self,*args,**kwargs):
        pk = kwargs.get('pk')
        book = Book.objects.filter(id=pk).first()
        book_ser = mySerializers.BookSerializers(instance=book)
        return Response(book_ser.data)
    #修改
    def put(self,request,*args,**kwargs):
        response_msg = {'status': 100, 'msg': '成功'}
        # 找到这个对象
        pk = kwargs.get('pk')
        book = Book.objects.filter(id=pk).first()
        # 得到一个序列化类的对象
        # boo_ser=BookSerializer(book,request.data)
        boo_ser = mySerializers.BookSerializers(instance=book, data=request.data)

        # 要数据验证(回想form表单的验证)
        if boo_ser.is_valid():  # 返回True表示验证通过
            boo_ser.save()  # 报错
            response_msg['data'] = boo_ser.data
        else:
            response_msg['status'] = 101
            response_msg['msg'] = '数据校验失败'
            response_msg['data'] = boo_ser.errors

        return Response(response_msg)

    def delete(self,*args,**kwargs):
        pk = kwargs.get('pk')
        ret=Book.objects.filter(pk=pk).delete()
        return Response({'status':100,'msg':'删除成功'})

#查询所有
class BooksAll(APIView):
    def get(self,*args,**kwargs):
        response_msg = {'status': 100, 'msg': '成功'}
        book = Book.objects.all()
        book_ser = mySerializers.BookSerializers(instance=book,many=True)
        response_msg['data'] = book_ser.data
        return Response(response_msg)

    def post(self,request,*args,**kwargs):
        response_msg = {'status': 100, 'msg': '成功'}
        book_ser = mySerializers.BookSerializers(data=request.data)
        if not book_ser.is_valid():
            response_msg['status'] = 101
            response_msg['msg'] = '增加数据失败'
            response_msg['err'] = book_ser.errors
            return Response(response_msg)
        book_ser.save()
        response_msg['date'] = book_ser.data
        return Response(response_msg)

自己定义的serializers的代码

from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from app01 import models
from app01.models import Reg,Book,Author,Publish

# 这里是序列化字段,想序列化哪个字段 就写上去
# 带字段验证
class PublishSerializers(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=32)
    phone = serializers.CharField(max_length=32)
    address = serializers.CharField(max_length=255)


# def check_name(data):
#     if data.startswith('sb'):
#         raise ValidationError('作者名字不能以sb开头')
#     else:
#         return data


class AuthorSerializers(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=32)
    # 还可以这么写
    # name = serializers.CharField(max_length=32,validators=[check_name])
    choices = ((0, '男'), (1, '女'), (2, '保密'))
    sex = serializers.ChoiceField(choices=choices)
    info = serializers.CharField(max_length=255)


class BookSerializers(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)  
    title = serializers.CharField(max_length=64)
    price = serializers.DecimalField(max_digits=8, decimal_places=2)
    publish_time = serializers.DateTimeField()
    publish_id = serializers.IntegerField()
)

    def validate_price(self, data):  # validate_字段名  接收一个参数
        # 如果价格小于10,就校验不通过
        # print(type(data))
        # print(data)
        if float(data) > 2:
            return data
        else:
            # 校验失败,抛异常
            raise ValidationError('价格太低')

    # def validate(self, validate_data):   # 全局钩子
    # print(validate_data)
    # author=validate_data.get('author')
    # publish=validate_data.get('publish')
    # if author == publish:
    #     raise ValidationError('作者名字跟出版社一样')
    # else:
    #     return validate_data
    # def get_publish(self, obj):  
    #     res = PublishSerializers(instance=obj.publish) 
    #     return res.data

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title')
        instance.price = validated_data.get('price')
        instance.publish_time = validated_data.get("publish_time")
        # instance.publish_id = validated_data.get("publish_id")

        instance.save()  # 保存
        return instance
    def create(self, validated_data):
        instance = Book.objects.create(**validated_data)
        return instance

 

这篇关于serializers的序列化和效验的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!