📌  相关文章
📜  序列化程序中的数字字段 – Django REST 框架

📅  最后修改于: 2022-05-13 01:55:13.821000             🧑  作者: Mango

序列化程序中的数字字段 – Django REST 框架

在 Django REST Framework 中,序列化的概念是将 DB 数据转换为 javascript 可以使用的数据类型。每个序列化程序都带有一些将要处理的字段(条目)。例如,如果您有一个名为 Employee 的类,其字段为 Employee_id、Employee_name、is_admin 等。那么,您将需要 AutoField、CharField 和 BooleanField 来通过 Django 存储和操作数据。同样,序列化器也以相同的原理工作,并具有用于创建序列化器的字段。
本文围绕 Django REST 框架中的序列化程序中的数字字段展开。有三个主要字段——IntegerField、FloatField 和 DecimalField。

整数字段

IntegerField 基本上是一个整数字段,用于根据 Python 的int实例验证输入。它与 IntegerField – Django 模型相同
它有以下论点——

  • max_value验证提供的数字不大于此值。
  • min_value验证提供的数字不小于此值。

句法 -

field_name = serializers.IntegerField(*args, **kwargs)

浮点场

FloatField 基本上是一个浮点字段,它根据 Python 的浮点实例验证输入。它与 FloatField – Django 模型相同
它有以下论点——

  • max_value验证提供的数字不大于此值。
  • min_value验证提供的数字不小于此值。

句法 -

field_name = serializers.FloatField(*args, **kwargs)

十进制字段

DecimalField 基本上是一个十进制字段,用于根据 Python 的十进制实例验证输入。它与 DecimalField – Django 模型相同
它有以下论点——

  • max_digits数字中允许的最大位数。它必须是 None 或大于或等于 decimal_places 的整数。
  • decimal_places与数字一起存储的小数位数。
  • max_value验证提供的数字不大于此值。
  • min_value验证提供的数字不小于此值。
  • localize设置为 True 以启用基于当前语言环境的输入和输出本地化。

句法 -

field_name = serializers.DecimalField(*args, **kwargs)

如何在序列化程序中使用数字字段?

为了解释数字字段的用法,让我们使用相同的项目设置 – 如何使用 Django Rest Framework 创建基本 API?
现在您的项目中有一个名为 serializers 的文件,让我们创建一个以 IntegerField、FloatField 和 DecimalField 作为字段的序列化程序。

Python3
# import serializer from rest_framework
from rest_framework import serializers
 
class Geeks(object):
    def __init__(self, integer, float_number, decimal_number):
        self.integer = integer
        self.float_number = float_number
        self.decimal_number = decimal_number
 
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # initialize fields
    integer = serializers.IntegerField()
    float_number = serializers.FloatField()
    decimal_number = serializers.DecimalField()


现在让我们创建一些对象并尝试序列化它们并检查它们是否真的在工作,运行,-

Python manage.py shell

现在,在 shell 中运行以下Python命令

# import everything from serializers
>>> from apis.serializers import *

# create a object of type Geeks
>>> obj = Geeks(123, 123.10, 123.123)

# serialize the object
>>> serializer = GeeksSerializer(obj)

# print serialized data
>>> serializer.data
{'integer': 123, 'float_number': 123.1, 'decimal_number': '123.1230'}

这是终端上所有这些操作的输出 -

序列化程序中的数字字段-Django-REST-Framework

数字字段验证

请注意,这些字段的主要座右铭是传递验证,例如 IntegerField 仅将数据验证为 Python 的 int。让我们检查一下这些验证是否有效——

# Create a dictionary and add invalid values
>>> data={}
>>> data['integer'] = 10
>>> data['float_number'] = "String"
>>> data['decimal_number'] = 123

# dictionary created
>>> data
{'integer': 10, 'float_number': 'String', 'decimal_number': 123}

# deserialize the data
>>> serializer = GeeksSerializer(data=data)

# check if data is valid
>>> serializer.is_valid()
False

# check the errors
>>> serializer.errors
{'float_number': [ErrorDetail(string='A valid number is required.', 
code='invalid')]}
}

以下是这些命令的输出,清楚地显示 email 和 phone_number 无效 –

数字字段-in-serializres-Django-REST-Framework

高级概念

验证是反序列化而不是序列化的一部分。如前所述,序列化是将已生成的数据转换为另一种数据类型的过程,因此不需要这些默认验证。反序列化需要验证,因为数据需要保存到数据库或指定的任何其他操作。因此,如果您使用这些有效的字段序列化数据。

序列化器字段中的核心参数

.math-table { 边框折叠:折叠;宽度:100%; } .math-table td { 边框:1px 实心 #5fb962;文本对齐:左!重要;填充:8px; } .math-table th { 边框:1px 实心 #5fb962;填充:8px; } .math-table tr>th{ 背景颜色:#c6ebd9;垂直对齐:中间; } .math-table tr:nth-child(odd) { background-color: #ffffff; }

ArgumentDescription
read_onlySet 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_onlySet 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.
requiredSetting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
defaultIf set, this gives the default value that will be used for the field if no input value is supplied.
allow_nullNormally 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.
sourceThe name of the attribute that will be used to populate the field.
validatorsA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messagesA dictionary of error codes to error messages.
labelA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_textA text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initialA value that should be used for pre-populating the value of HTML form fields.