Django Rest Framework如何发布日期字段 [英] Django Rest Framework how to post date field

查看:126
本文介绍了Django Rest Framework如何发布日期字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发布带有字段 date 的JSON请求:

I want to post JSON request with field date:

{
    "date":"2015-02-11T00:00:00.000Z"
}

这是从 Date 对象自动转换的字符串,我不想裁剪 T00:00:00.000Z 在前端手动进行。

It's the string is automatically converted from Date object and I don't want to crop the part T00:00:00.000Z manually at frontend.

但是,如果我发布了这样的请求,则DateField的Django Rest Framework验证程序会说我该日期的格式无效。

But if I post such request, Django Rest Framework validator of DateField will say me, that date has invalid format.

我的模型:

class Event(models.Model):
    name = models.CharField('Name', max_length=40, blank=True, null=True)
    date = models.DateField('Date', blank=True, null=True)

我的序列化器:

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = ('id', 'name', 'date')

解决此问题的正确方法是什么?

What is the right way to solve this problem?

推荐答案

您可以使用不同的格式(不同于隐式使用的默认格式)修改序列化程序中的日期字段。

You can modify your date field in your serializer with a different format (different from the default one, which you are using implicitly).

更多信息:

https://www.django-rest-framework.org/api-guide/fields/#datefield

https://docs.python.org/3/ library / datetime.html#strftime-and-strptime-behavior

from rest_framework import serializers, fields


class EventSerializer(serializers.ModelSerializer):

    date = fields.DateField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ'])

    class Meta:
        model = Event
        fields = ('id', 'name', 'date')

请注意,如果您需要解析除在UTC(时间戳末尾为Z)中,您将需要更多自定义 DateField

Note that if you need to parse timestamps other than in UTC (Z at the end of your timestamp), you will need to customize DateField a bit more.

正如注释中提到的@nitrovatter一样,日期输入格式也可以在设置中配置为默认情况下影响每个序列化程序。例如:

As @nitrovatter mentioned in the comments, the date input formats can also be configured in the settings to affect every serializer by default. For example:

REST_FRAMEWORK = {
    'DATE_INPUT_FORMATS': ['iso-8601', '%Y-%m-%dT%H:%M:%S.%fZ'],
}

这篇关于Django Rest Framework如何发布日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆