Django : how to set DateTimeFiel
背景:
在多种Model的定义场景中,需要在数据库中记录每一条记录的创建时间和修改更新时间, 在Django中常见的操作如下:
class Order(models.Model):
goods = models.ManyToManyField(Book, through='OrderGoodsDetail')
user = models.ForeignKey(Profile, on_delete=models.PROTECT)
remark = models.TextField(null=True, default='', blank=True)
orderId = models.CharField(max_length=32, blank=True)
createTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(auto_now=True)
在如上代码块中, creatTime在记录创建的时候由django自动生成时间数据, updateTime在记录修改的时候由django自动更新。
关于 auto_now_add 和 auto_now 的详细描述,援引官网描述如下:
- auto_now
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when callingModel.save()
. The field isn’t updated when making updates to other fields in other ways such asQuerySet.update()
, though you can specify a custom value for the field in an update like that.
*auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is alwaysused; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True
:
- For
DateField
:default=date.today
- fromdatetime.date.today()
- For
DateTimeField
:default=timezone.now
- fromdjango.utils.timezone.now()
可以参考网页auto_now_add和auto_now
问题:
笔者使用如下serializer对model进行序列化
class OrderSerializer(DynamicFieldsModelSerializer):
createTime = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
updateTime = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
...
发现记录创建的时间并不是使用的是本地时间。如实际创建时间是 2018/03/26 16:49分, 在序列化之后展示的时间却是 2018-03-26 08:49 分。笔者查看了数据库中的存储的数据如下, 序列化的数据确实和数据库中的数据保持一致。
第5列为createTime,第6列为updateTime
问题就来了:
如果需要显示为北京时间, 该怎么做呢?
问题解决:
在project的settings.py文件中做如下设置:
TIME_ZONE = ‘Asia/Shanghai'
USE_TZ = False
按照以上设置之后, Django在创建记录的时候, 就会按照本地时间的值初始化DateTimefield中的值。
来自官网TIME_ZONE setting的解释如下:
When USE_TZ
is False
, this is the time zone in which Django will store all datetimes. When USE_TZ
is True
, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.