首页 > 编程 > Python > 正文

django Serializer序列化使用方法详解

2020-02-15 23:13:34
字体:
来源:转载
供稿:网友

Serializer序列化器

定义Serializer

1. 定义方法

Django REST framework中的Serializer使用类来定义,须继承自rest_framework.serializers.Serializer。

例如,我们已有了一个数据库模型类BookInfo

class BookInfo(models.Model):  btitle = models.CharField(max_length=20, verbose_name='名称')  bpub_date = models.DateField(verbose_name='发布日期', null=True)  bread = models.IntegerField(default=0, verbose_name='阅读量')  bcomment = models.IntegerField(default=0, verbose_name='评论量')  image = models.ImageField(upload_to='booktest', verbose_name='图片', null=True)

我们想为这个模型类提供一个序列化器,可以定义如下:

class BookInfoSerializer(serializers.Serializer):  """图书数据序列化器"""  id = serializers.IntegerField(label='ID', read_only=True)  btitle = serializers.CharField(label='名称', max_length=20)  bpub_date = serializers.DateField(label='发布日期', required=False)  bread = serializers.IntegerField(label='阅读量', required=False)  bcomment = serializers.IntegerField(label='评论量', required=False)  image = serializers.ImageField(label='图片', required=False)

注意:serializer不是只能为数据库模型类定义,也可以为非数据库模型类的数据定义。serializer是独立于数据库之外的存在。

2. 字段与选项

常用字段类型:

字段 字段构造方式
BooleanField BooleanField()
NullBooleanField NullBooleanField()
CharField CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
EmailField EmailField(max_length=None, min_length=None, allow_blank=False)
RegexField RegexField(regex, max_length=None, min_length=None, allow_blank=False)
SlugField SlugField(maxlength=50, min_length=None, allow_blank=False)
正则字段,验证正则模式 [a-zA-Z0-9-]+
URLField URLField(max_length=200, min_length=None, allow_blank=False)
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"
IPAddressField IPAddressField(protocol='both', unpack_ipv4=False, **options)
IntegerField IntegerField(max_value=None, min_value=None)
FloatField FloatField(max_value=None, min_value=None)
DecimalField DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)
max_digits: 最多位数
decimal_palces: 小数点位置
DateTimeField DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
DateField DateField(format=api_settings.DATE_FORMAT, input_formats=None)
TimeField TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
DurationField DurationField()
ChoiceField ChoiceField(choices)
choices与Django的用法相同
MultipleChoiceField MultipleChoiceField(choices)
FileField FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
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=)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表