Django 模型 DateTimeField 设置 auto_now_add 格式或修改序列化器

Django model DateTimeField set auto_now_add format or modify the serializer

我的模型中有这个字段:

createdTime = models.DateTimeField(_('Creation date'), help_text=_('Date of the creation'),
                                   auto_now_add=True, blank=True)

并以这种格式保存:

2016-05-18T15:37:36.993048Z

所以我想把它转换成这种格式DATE_INPUT_FORMATS = ('%d-%m-%Y %H:%M:S')但我不知道在哪里做。

我有一个简单的序列化器class,我可以覆盖它来修改格式吗?或者创建一个 get_date() 模型方法?

class ObjectSerializer(serializers.ModelSerializer):
    """
    Serializer for object.
    """
    class Meta:
        model = Object

我的设置:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'

USE_I18N = True

USE_L10N = False

USE_TZ = False

在您的 settings.py 中设置 DATETIME_FORMAT 作为指定 here

The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead

settings.py 的日期部分之后应该如下所示:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' 
USE_L10N = False
USE_TZ = False # if you plan to disable timezone support

或者,您可以在检索后手动更改格式,方法是:

import datetime

datetime_str = '2016-05-18T15:37:36.993048Z'
old_format = '%Y-%m-%dT%H:%M:%S.%fZ'
new_format = '%d-%m-%Y %H:%M:%S'

new_datetime_str = datetime.datetime.strptime(datetime_str, old_format).strftime(new_format)
print(new_datetime_str)
#'18-05-2016 15:37:36'

此转换可以作为您建议的 get_date() 方法添加到您的序列化程序或模型中

您可以在模型的序列化程序中定义 DateTimeField 的格式 (在 django 3.1.5 上检查):

class ObjectSerializer(serializers.ModelSerializer):
   createdTime = serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S")

   class Meta:
      model = Object
      fields = '__all__'