首页 > 其他分享 >drf 04

drf 04

时间:2023-02-02 21:45:28浏览次数:56  
标签:serializers name 04 max publish length CharField drf

序列化类常用字段和字段参数

常用字段类

#1 BooleanField          BooleanField()

#2 NullBooleanField      NullBooleanField()

#3 CharField    CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)

#4 EmailField    EmailField(max_length=None, min_length=None, allow_blank=False)

#5 RegexField    RegexField(regex, max_length=None, min_length=None, allow_blank=False)

#6 SlugField    SlugField(max_length=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+

#7 URLField    URLField(max_length=200, min_length=None, allow_blank=False)

#8 UUIDField    UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"

#9 IPAddressField    IPAddressField(protocol=’both’, unpack_ipv4=False, **options)

#10 IntegerField    IntegerField(max_value=None, min_value=None)

#11 FloatField    FloatField(max_value=None, min_value=None)

#12 DecimalField    DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置

#13 DateTimeField    DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)

#14 DateField    DateField(format=api_settings.DATE_FORMAT, input_formats=None)

#15 TimeField    TimeField(format=api_settings.TIME_FORMAT, input_formats=None)

#16 DurationField    DurationField()

#17 ChoiceField    ChoiceField(choices) choices与Django的用法相同

#18 MultipleChoiceField    MultipleChoiceField(choices)

#19 FileField    FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

#20 ImageField    ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

# 重要的,后续讲到
    - ListField    
             ListField(child=, min_length=None, max_length=None)
    - DictField    
             DictField(child=)


# 需要掌握记住的:
     - CharField  IntegerField  DecimalField  DateTimeField BooleanField ListField DictField

常用字段参数

- 选项参数:

# CharField及其子类的(EmailField) ---》反序列化的校验,字段自己的规则
    max_length    最大长度
    min_lenght    最小长度
    allow_blank    是否允许为空
    trim_whitespace    是否截断空白字符

# IntegerField
    max_value    最小值
    min_value    最大值

    
# 所有字段类都有的
required       表明该字段在反序列化时必须输入,默认True
default        反序列化时使用的默认值
allow_null     表明该字段是否允许传入None,默认False
validators     该字段使用的验证器
----看一眼忘掉-----
error_messages 包含错误编号与错误信息的字典
label          用于HTML展示API页面时,显示的字段名称
help_text      用于HTML展示API页面时,显示的字段帮助提示信息


# 重点:
read_only    表明该字段仅用于序列化输出,默认False
write_only    表明该字段仅用于反序列化输入,默认False


# 反序列化校验执行流程
    -1.先执行字段自己的校验规则
         最大长度,最小长度,是否为空,是否必填,最小数字...
    -2.validators=[方法,] 
         单独给这个字段加校验规则: 

name=serializers.CharField(validators=[方法,]) -3.局部钩子校验规则 -4.全局钩子校验规则

序列化高级用法source(了解即可)

# 1.创建模型类,关联表关系
from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

    publish = models.ForeignKey(to='Publish',on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')

class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

class Author(models.Model):
    name = models.CharField(max_length=32)
    phone = models.CharField(max_length=11)
# 2.迁移表数据

# 3.序列化定制字段名字source
from rest_framework import serializers

class BookSerializer(serializers.Serializer):
    # 字段参数,通用的一些限制
    # 所有字段都可以通过source指定定制字段
    name_real = serializers.CharField(max_length=8,source='name')
    price_real = serializers.CharField(source='price')
    # 一对一,自己字段直接写
    # 一对多,关联字段直接点
    publish = serializers.CharField(source='publish.name')
    # 多对多,搞不了,source不能用
    authors = serializers.CharField(source='author.all')
    

 序列化高级用法之定制字段的两种方式

# 方法一:SerializerMethodField定制
from rest_framework import serializers

class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=8)
    price = serializers.CharField()

    # 定制返回格式:方式1
    publish_detail = serializers.SerializerMethodField()

    def get_publish_detail(self,obj):
        return {'name':obj.publish.name,'addr': obj.publish.addr}

    # 定制返回格式:方式2
    author_list = serializers.SerializerMethodField()

    def get_author_list(self, obj):
        l = []
        for author in obj.authors.all():
            l.append({'name': author.name, 'phone': author.phone})
        return l

# 高级序列化之SerializerMethodField
"""
{
    "name": "西游记",
    "price": "77",
    "publish":{"name":"北京出版社","addr":"北京"},
    authors:[{name:lqz,phone:1111},{name:罗贯中,phone:1111}]
}

"""
# 方法二:在表模型中定制
# models.py

from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

    publish = models.ForeignKey(to='Publish',on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')

    def publish_detail(self):
        return {'name': self.publish.name,'addr': self.publish.addr}

    def author_list(self):
        l = []
        for author in self.authors.all():
            l.append({'name': author.name,'phone':author.phone})
        return l



# serializers.py    : 序列化类

from rest_framework import serializers

class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=8)
    price = serializers.CharField()

    publish_detail = serializers.DictField()
    author_list = serializers.ListField()

多表关联反序列化保存

新增接口

# 视图类 views.py
from rest_framework import serializers
from .models import Book,Author,Publish

class BookView(APIView):
    # def get(self,request):
    #     books = Book.objects.all()
    #     ser = BookSerializer(instance=books, many=True)
    #     return Response(ser.data)
    def post(self,request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code':100,'msg':'新增成功'})
        else:
            return Response({'code':101,'msg':ser.errors})

# 序列化类 serializers.py
class BookSerializer(serializers.Serializer):
# name和price  可用来序列化,也可用来反序列化,又读又写,不用加read_only,write_only
    name = serializers.CharField(max_length=8)
    price = serializers.CharField()
    # 只用来序列化   只读 read_only
    publish_detail = serializers.DictField(read_only=True)
    author_list = serializers.ListField(read_only=True)
    # 只用来反序列化 只写 write_only
    publish = serializers.CharField(write_only=True)
    authors = serializers.ListField(write_only=True)
    # 新增    要重写create方法
    def create(self,validated_data):
        # validated_data是校验过后的数据,
        # 新增一本图书
        book = Book.objects.create(name=validated_data.get('name'),price=validated_data.get('price'),
                                   publish_id = validated_data.get('publish'))
        # price = validated_data.get('price'),
        # publish_id = validated_data.get('publish')
        # 把作者与书关联
        book.authors.add(*validated_data.get('authors'))
        return book

修改更新接口

# 视图类 views.py
from rest_framework.views import APIView
from .models import Book
from .serializers import BookSerializer
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError

class BookDetailView(APIView):
    def put(self,request,pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(data=request.data,instance=book)
        if ser.is_valid():
            ser.save()
            return Response({'code':100,'msg':'修改成功'})
        else:
            return Response({'code': 101, 'msg':ser.errors})

# 序列化类  serializers.py
from rest_framework import serializers
from .models import Book,Author,Publish
class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=8)
    price = serializers.CharField()
    # 只用来序列化   只读 read_only
    publish_detail = serializers.DictField(read_only=True)
    author_list = serializers.ListField(read_only=True)
    # 只用来反序列化 只写 write_only
    publish = serializers.CharField(write_only=True)
    authors = serializers.ListField(write_only=True)

    # 修改要重写update
    def update(self,instance,validated_data):
        instance.name = validated_data.get('name')
        instance.price = validated_data.get('price')
        instance.publish_id = validated_data.get('publish')
        # 先清空,在添加
        authors = validated_data.get('authors')
        instance.authors.clear()
        instance.authors.add(*authors)
        instance.save()
        return instance

反序列化字段校验其他

# 步骤:
    -1 字段自己的:举例:name = serializers.CharField(max_length=8, error_messages={'max_length': '太长了'})
    -2 validators=[方法,]   忽略掉
    -3 局部钩子
    -4 全局钩子

ModelSerializer使用

# ModelSerializer 继承自Serializer
   -跟表模型强关联
   -大部分请求,不用写create和update了

# ModelSerializer的使用
class BookSerializer(serializers.ModelSerializer):
    # 和表有关联
    class Meta:
        model = Book  # 跟book表建立了关系     序列化类和表模型类
        # 序列化所有Book中的字段  id name price publish authors
        # fields = '__all__'  
        # 序列化所有Book中的name和price字段字段
        fields = ['name', 'price', 'publish_detail', 'author_list', 'publish', 'authors']  

        # 定制name反序列化时,最长不能超过8  ,给字段类加属性
        # 方式一
        extra_kwargs = {'name': {'max_length': 8},
                        'publish_detail': {'read_only': True},
                        'author_list': {'read_only': True},
                        'publish': {'write_only': True},
                        'authors': {'write_only': True},
                        }

         # 如果Meta写了__all__ ,就相当于,复制了表模型中的所有字段,放在了这里,做了个映射
        # name = serializers.CharField(max_length=32)
        # price = serializers.CharField(max_length=32)

       # 定制name反序列化时,最长不能超过8   给字段类加属性---方式二,重写name字段
       # name = serializers.CharField(max_length=8)

       # 同理,所有的read_only和wirte_only都可以通过重写或使用extra_kwargs传入

       # 最后,把这个序列化类写成跟之前一模一样项目
       # publish_detail = serializers.SerializerMethodField(read_only=True)
       # def get_publish_detail(self, obj):
       #     return {'name': obj.publish.name, 'addr': obj.publish.addr}
       # author_list = serializers.SerializerMethodField(read_only=True)
       # def get_author_list(self, obj):
       #     l = []
       #     for author in obj.authors.all():
       #         l.append({'name': author.name, 'phone': author.phone})
       #     return l

       # 局部钩子和全局钩子跟之前完全一样
       def validate_name(self, name):
           if name.startswith('sb'):
               raise ValidationError('不能sb')

           else:
               return name

 

标签:serializers,name,04,max,publish,length,CharField,drf
From: https://www.cnblogs.com/juzijunjun/p/17087510.html

相关文章

  • drf day04 序列化高级用法、ModelSerializer、字段参数source
    一个小作业自己写代码,让原生的request能实现request.data传值思路:写装饰器,装饰request.data,做到2+1都是request.datadefMyRequest(func):definner(request,*......
  • drf-4
    序列化类常用字段和字段参数(了解)#序列化类---》字段类CharField,除此之外还有哪些其他的#序列化类---》字段类,字段类上,传属性的,序列化类上,也可以写属性【models.Cha......
  • 备库open数据库时报错ORA-10458、ORA-16191
    问题描述:备库open数据库时报错ORA-10458、ORA-16191,如下所示:系统:centos7.9数据库:oracle11.2.0.4主机名:主库leo-oel150+备库leo-oel1511、异常重现SYS@orcl151>alterdat......
  • drf-3
    drf整体内容#1.入门规范web开发模式api接口接口测试工具restful规范序列化反序列化drf快速使用APIView,Request类drf把Django的好多东西都重写了#2.序列化组件(重......
  • drf快速编写接口
    创建序列化类字段参数fromrest_frameworkimportserializersfromapp01.modelsimportBook举例:classBooksSerializer(serializers.Serializer):name=seria......
  • 【Django drf】序列化器总结
    目录序列化器字段外键字段自定义序列化在模型类中写方法在序列化类中写方法反序列化外键字段反序列化保存序列化器字段序列化中的字段可以根据用途分为三种:既用于序列......
  • django框架之drf:04、序列化器常用字段及参数,序列化器高级用法之source、定制字段数据
    Django框架之drf目录Django框架之drf一、序列化器常用字段及参数1、常用字段2、常用字段参数3、字段参数针对性分类二、序列化器高级用法之source1、定制字段名三、定制......
  • drf-序列化字段及参数、序列化和反序列化高级用法、ModelSerializer使用
    1.序列化类常用字段和字段参数1.1常用字段类1.BooleanField2NullBooleanField3CharFieldCharField(max_length=None,min_length=None,allow_blank=False,trim_......
  • DRF 04 序列化反序列化的功能实现
    作业:#原生的django中request中是没有data的,但是通过下面的这个装饰器就能实现通过点data也能获取到数据defwrapper(func):#通过装饰器做装饰视图的,以后都会有req......
  • drf从入门到精通---day04
    昨日回顾#1APIView---->drf提供的,继承了原来的View,以后如果写视图类,都继承APIView及其子类#2APIView执行流程 -1去除了csrf认证-2包装了新的Request对象---......