在 Django 中,模型有一个默认的时间戳字段吗? [英] In django do models have a default timestamp field?
本文介绍了在 Django 中,模型有一个默认的时间戳字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 django 中 - 是否有所有对象的默认时间戳字段?也就是说,我是否必须在我的模型中为创建于"明确声明一个时间戳"字段 - 或者有没有办法自动获得它?
In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a 'timestamp' field for 'created on' in my Model - or is there a way to get this automagically?
推荐答案
默认情况下没有这样的东西,但添加一个非常容易.只需使用 DateTimeField
类中的 auto_now_add
参数:
No such thing by default, but adding one is super-easy. Just use the auto_now_add
parameter in the DateTimeField
class:
created = models.DateTimeField(auto_now_add=True)
您还可以将 auto_now
用于更新日期"字段.检查 auto_now
此处.
You can also use auto_now
for an 'updated on' field.
Check the behavior of auto_now
here.
对于 auto_now_add
此处.
具有两个字段的模型将如下所示:
A model with both fields will look like this:
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
这篇关于在 Django 中,模型有一个默认的时间戳字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文