python - 设置django rest框架配置的DatetimeField格式

标签 python django python-2.7 serialization django-rest-framework

我尝试使用 DRF 序列化程序来序列化模型对象。我发现对象中的 DatetimeField 不会输出 ISO-8601 格式的 "2015-10-21T09:28:53.769000Z"

我查找DRF文档为什么我不能输出ISO-8601格式。根据datetimefield说:

format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python

这意味着如果我从不设置 DATETIME_FORMAT 参数,它默认输出 iso-8601 格式?还没有,还是没有变化。

当我尝试如下编写 django 项目的设置时:

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "iso-8601",
}

或者我在 DatetimeField 参数中写如下:

class UserSerializer(...):
    last_login = DatetimeField(format='iso-8601')
    class Meta:
        model = User
        fields = ('email', 'displayname', 'is_active',
                  'date_joined', 'last_login')

还是没有变化。

有人知道怎么设置吗?

最佳答案

如果您不知道会发生什么并且您仍然不喜欢它,我可以在设置中定义一个日期时间格式,如下所示:

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ",
}

关于python - 设置django rest框架配置的DatetimeField格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277537/

相关文章:

python - 在 Python 中快速对图像运行滑动窗口方法的技巧

python: "import Image"仅在以 root 身份执行时有效

python - 在python中使用装饰器时出现位置参数错误

突然崩溃后Python文件为空

python - Django - 使用unicode主键获取对象

django - 不能同时设置 `read_only` 和 `write_only`

python - Anaconda 和 Pycharm 有什么区别?

python - NumPy 中向量的叉积

django - 无法备份我的 PostgreSQL 数据库 [用户 "USER"的对等身份验证失败]

python - 如何将测试 api 的 Locust 结果写入文件