在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
默认情况下没有这样的东西,但添加一个非常容易。只需使用
DateTimeField
类中的auto_now_add
参数即可:您还可以将
auto_now
用于“更新日期”字段。检查
auto_now
此处。对于
auto_now_add
这里。具有这两个字段的模型将如下所示:
No such thing by default, but adding one is super-easy. Just use the
auto_now_add
parameter in theDateTimeField
class:You can also use
auto_now
for an 'updated on' field.Check the behavior of
auto_now
here.For
auto_now_add
here.A model with both fields will look like this:
Automagically 听起来不像 django 默认情况下会做的事情。它不会强迫您需要时间戳。
如果您不想忘记时间戳/字段名等,我会构建一个抽象基类并从中继承所有模型。
导入
wherever.TimeStampedModel
似乎并不多django.db.models.Model 的Automagically doesn't sound like something django would do by default. It wouldn't force you to require a timestamp.
I'd build an abstract base class and inherit all models from it if you don't want to forget about the timestamp / fieldname, etc.
It doesn't seem like much to import
wherever.TimeStampedModel
instead ofdjango.db.models.Model
如果您使用 django-extensions (这是一个很好的应用程序,可以向django-admin.py 命令行助手)您可以通过继承 他们的 TimeStampedModel 或使用他们的 自定义时间戳字段
If you are using django-extensions (which is a good app for adding functionality to the django-admin.py command line helper) you can get these model fields for free by inheriting from their TimeStampedModel or using their custom TimeStamp fields
你可以尝试 django-extensions
如果你想使用时间戳抽象模型,
它还有其他抽象模型。你也可以用它。
You can try django-extensions
if you want to use time-stamp abstract model
It has other abstract models. you can use that too.
如果您希望能够修改此字段,请设置以下内容而不是
auto_now_add=True:
For Date
For DateTime
If you want to be able to modify this field, set the following instead of
auto_now_add=True:
For Date
For DateTime
由于您可能在模型中使用 ID,因此以这种方式使用它们是安全的。
然后将 TimeStampedModel 导入到您想要使用它们的任何模型中,例如
Since you might be using IDs with your models, it's safe to use them this way.
Then import the TimeStampedModel in any model you want to use them, eg
我想我会同意
我需要一些关于使用的澄清
I think i would go with
I need some clarifications on using