序列化器——Django REST 框架
Django REST Framework 中的序列化器负责将对象转换为 javascript 和前端框架可以理解的数据类型。序列化器还提供反序列化,允许在首先验证传入数据后将解析的数据转换回复杂类型。 REST 框架中的序列化程序的工作方式与 Django 的 Form 和 ModelForm 类非常相似。最常用的两个主要序列化器是 ModelSerializer 和 HyperLinkedModelSerialzer。
本文围绕如何在 Django REST 框架中从头开始使用序列化器到高级序列化器字段和参数。它假定您熟悉如何使用 Django REST 框架启动项目?
- 创建和使用序列化器
- 模型序列化器
- HyperLinkedModelSerializer
- 序列化器字段
- 序列化器字段中的核心参数
创建和使用序列化器
创建一个基本的序列化器
要创建一个基本的序列化器,需要从 rest_framework 导入序列化器类并为序列化器定义字段,就像在 Django 中创建表单或模型一样。
例子
Python3
# import serializer from rest_framework
from rest_framework import serializers
# create a serializer
class CommentSerializer(serializers.Serializer):
# initialize fields
email = serializers.EmailField()
content = serializers.CharField(max_length = 200)
created = serializers.DateTimeField()
Python3
# import datetime object
from datetime import datetime
# create a class
class Comment(object):
def __init__(self, email, content, created = None):
self.email = email
self.content = content
self.created = created or datetime.now()
# create a object
comment = Comment(email ='leila@example.com', content ='foo bar')
Python3
class SerializerName(serializers.ModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
Python3
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
Python3
class SerializerName(serializers.HyperlinkedModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
Python3
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
通过这种方式,可以根据所需字段为任何特定实体或对象声明序列化程序。序列化器可用于序列化和反序列化数据。
使用 Serializer 序列化数据
现在可以使用 CommentSerializer 来序列化评论或评论列表。同样,使用 Serializer 类看起来很像使用 Form 类。让我们首先创建一个 Comment 类来创建一个可以被我们的序列化器理解的 comment 类型的对象。
Python3
# import datetime object
from datetime import datetime
# create a class
class Comment(object):
def __init__(self, email, content, created = None):
self.email = email
self.content = content
self.created = created or datetime.now()
# create a object
comment = Comment(email ='leila@example.com', content ='foo bar')
现在我们的对象已经准备好了,让我们尝试序列化这个评论对象。运行以下命令,
Python manage.py shell
现在运行以下代码
# import comment serializer
>>> from apis.serializers import CommentSerializer
# import datetime for date and time
>>> from datetime import datetime
# create a object
>>> class Comment(object):
... def __init__(self, email, content, created=None):
... self.email = email
... self.content = content
... self.created = created or datetime.now()
...
# create a comment object
>>> comment = Comment(email='leila@example.com', content='foo bar')
# serialize the data
>>> serializer = CommentSerializer(comment)
# print serialized data
>>> serializer.data
现在让我们检查一下输出,
要查看有关如何创建和使用序列化程序的更多信息,请访问 - 创建和使用序列化程序
模型序列化器
ModelSerializer 类提供了一种快捷方式,可让您自动创建具有与 Model 字段对应的字段的 Serializer 类。
ModelSerializer 类与常规 Serializer 类相同,除了:
- 它将根据模型自动为您生成一组字段。
- 它将自动为序列化程序生成验证器,例如 unique_together 验证器。
- 它包括 .create() 和 .update() 的简单默认实现。
句法 -
Python3
class SerializerName(serializers.ModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
例子 -
Python3
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
默认情况下,类上的所有模型字段都将映射到相应的序列化器字段。
要查看如何在项目中使用 ModelSerializer,请访问 - 序列化程序中的 ModelSerializer - Django REST Framework。
超链接模型序列化器
HyperlinkedModelSerializer 类与 ModelSerializer 类类似,只是它使用超链接而不是主键来表示关系。默认情况下,序列化程序将包含一个 url 字段而不是主键字段。 url 字段将使用 HyperlinkedIdentityField 序列化器字段表示,模型上的任何关系都将使用 HyperlinkedRelatedField 序列化器字段表示。
句法 -
Python3
class SerializerName(serializers.HyperlinkedModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
例子 -
Python3
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
要查看如何在您的项目中使用 HyperLinkedModelSerializer,请访问 – HyperlinkedModelSerializer in serializers – Django REST Framework。
序列化器字段
Field Name | Description |
---|---|
BooleanField | A boolean field used to wrap True or False values. |
NullBooleanField | A boolean field that accepts True, False and Null values. |
CharField | CharField is used to store text representation. |
EmailField | EmailField is also a text representation and it validates the text to be a valid e-mail address. |
RegexField | As the name defines, RegexField matches the string to a particular regex, else raises an error. |
URLField | URLField is basically a RegexField that validates the input against a URL matching pattern. |
SlugField | SlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+. |
IPAddressField | IPAddressField is a field that ensures the input is a valid IPv4 or IPv6 string. |
IntegerField | IntegerField is basically a integer field that validates the input against Python’s int instance. |
FloatField | FloatField is basically a float field that validates the input against Python’s float instance. |
DecimalField | DecimalField is basically a decimal field that validates the input against Python’s decimal instance. |
DateTimeField | DateTimeField is a serializer field used for date and time representation. |
DateField | DateField is a serializer field used for date representation. |
TimeField | Timefield is a serializer field used for time representation. |
DurationField | DurationField is a serializer field used for duration representation. |
ChoiceField | ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices. |
MultipleChoiceField | MultipleChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices. |
FileField | FileField is basically a file representation. It performs Django’s standard FileField validation. |
ImageField | ImageField is an image representation.It validates the uploaded file content as matching a known image format. |
ListField | ListField is basically a list field that validates the input against a list of objects. |
JSONField | JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives. |
HiddenField | HiddenField is a field class that does not take a value based on user input, but instead takes its value from a default value or callable. |
DictField | DictField is basically a dictionary field that validates the input against a dictionary of objects. |
序列化器字段中的核心参数
Django 中的序列化器字段与 Django 表单字段和 Django 模型字段相同,因此需要某些参数来操作这些字段的行为。Argument Description read_only Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization write_only Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. required Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. default If set, this gives the default value that will be used for the field if no input value is supplied. allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. source The name of the attribute that will be used to populate the field. validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. error_messages A dictionary of error codes to error messages. label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements. initial A value that should be used for pre-populating the value of HTML form fields.