Django Rest Framework how to post date field

前端 未结 1 779
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 00:05

I want to post JSON request with field date:

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

It\'s the string is automatically c

1条回答
  •  一生所求
    2021-01-06 00:34

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

    More info:

    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')
    

    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.

    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'],
    }
    

    0 讨论(0)
提交回复
热议问题