📌  相关文章
📜  序列化程序中的日期和时间字段 – Django REST 框架

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

序列化程序中的日期和时间字段 – Django REST 框架

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

日期时间字段

DateTimeField 是用于日期和时间表示的序列化器字段。它与 – DateTimeField – Django 模型相同
它有以下论点——

  • format -- 表示输出格式的字符串。如果未指定,则默认为与 DATETIME_FORMAT 设置键相同的值,除非设置,否则将为“iso-8601”。设置为格式字符串表示 to_representation 返回值应强制转换为字符串输出。格式字符串如下所述。将此值设置为 None 表示Python日期时间对象应由 to_representation 返回。在这种情况下,日期时间编码将由渲染器确定。
  • input_formats – 表示可用于解析日期的输入格式的字符串列表。如果未指定,将使用 DATETIME_INPUT_FORMATS 设置,默认为 ['iso-8601']。
  • default_timezone -- 代表时区的 pytz.timezone。如果未指定并且启用了 USE_TZ 设置,则默认为当前时区。如果 USE_TZ 被禁用,那么 datetime 对象将是幼稚的。

句法 -

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

日期字段

DateField 是用于日期表示的序列化器字段。通常,需要存储日期,例如在博客模型中,每个帖子的日期都需要存储。此字段与 DateField – Django 模型相同
它有以下论点——

  • format -- 表示输出格式的字符串。如果未指定,则默认为与 DATE_FORMAT 设置键相同的值,除非设置,否则将为“iso-8601”。设置为格式字符串表示 to_representation 返回值应强制转换为字符串输出。格式字符串如下所述。将此值设置为 None 表示Python日期对象应由 to_representation 返回。在这种情况下,日期编码将由渲染器确定。
  • input_formats – 表示可用于解析日期的输入格式的字符串列表。如果未指定,将使用 DATE_INPUT_FORMATS 设置,默认为 ['iso-8601']。

句法 -

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

时间场

Timefield 是用于时间表示的序列化器字段。通常,需要存储日期,例如在博客模型中,每个帖子的时间都需要存储。
它有以下论点——

  • format -- 表示输出格式的字符串。如果未指定,则默认为与 TIME_FORMAT 设置键相同的值,除非设置,否则将为“iso-8601”。设置为格式字符串表示 to_representation 返回值应强制转换为字符串输出。格式字符串如下所述。将此值设置为 None 表示Python时间对象应由 to_representation 返回。在这种情况下,时间编码将由渲染器确定。
  • input_formats – 表示可用于解析日期的输入格式的字符串列表。如果未指定,将使用 TIME_INPUT_FORMATS 设置,默认为 ['iso-8601']。

句法 -

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

持续时间字段

DurationField 是用于表示持续时间的序列化器字段。该字段与 DurationField – Django 模型相同
它有以下论点——

  • max_value验证提供的持续时间不大于此值。
  • min_value验证提供的持续时间不小于此值。

句法 -

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

如何在序列化程序中使用日期和时间字段?

为了解释日期和时间字段的用法,让我们使用相同的项目设置 – 如何使用 Django Rest Framework 创建基本 API?
现在您的项目中有一个名为 serializers 的文件,让我们创建一个包含 DatetimeField、DateField、TimeField 和 DurationField 的序列化程序。

Python3
# import serializer from rest_framework
from rest_framework import serializers
 
class Geeks(object):
    def __init__(self, date_time, date, time, duration):
        self.date_time = date_time
        self.date = date
        self.time = time
        self.duration = duration
 
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # initialize fields
    date_time = serializers.DateTimeField()
    date = serializers.DateField()
    time = serializers.TimeField()
    duration = serializers.DurationField()


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

Python manage.py shell

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

# import everything from datetime
>>> from datetime import *

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

# create a object of type Geeks
>>> obj = Geeks(datetime.now(), date.today(), time(), timedelta(days=-1))

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

# print serialized data
>>> serializer.data
{'date_time': '2020-03-22T13:17:27.853707Z',
 'date': '2020-03-22', 'time': '00:00:00', 
 'duration': '-1 00:00:00'}

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

序列化程序中的日期和时间字段-Django-REST-Farmweork

日期和时间字段的验证

请注意,这些字段的主要座右铭是进行验证,例如 DateField 仅验证数据的日期。让我们检查一下这些验证是否有效——

# Create a dictionary and add invalid values
>>> data={}
>>> data['date_time'] = "invalid_date_time"
>>> data['date'] = date.today()
>>> data['time'] = time()
>>> data['duration'] = "invalid_duration"

# dictionary created
>>> data
{'date_time': 'invalid_date_time', 
'date': datetime.date(2020, 3, 22),
'time': datetime.time(0, 0), 
'duration': 'invalid_duration'}

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

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

# check the errors
>>> serializer.errors
{'date_time': [ErrorDetail(string='Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].', code='invalid')], 'duration': [ErrorDetail(strin
g='Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].', code='invalid')]}

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

序列化器中的日期和时间字段

高级概念

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

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

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.