Django:模型上次修改日期和修改计数 [英] Django: models last mod date and mod count
问题描述
我有一个名为 Blog
的Django模型。
I have a django model called Blog
.
我想在当前模型中添加一个针对last_modified_date的字段。我知道如何设置默认值,但是我希望通过管理界面修改博客条目时可以自动更新默认值。
I'd like to add a field to my current model that is for last_modified_date. I know how to set a default value, but I would like somehow for it to get automatically updated anytime I modify the blog entry via the admin interface.
是否有某种方法可以在保存每个管理站点时将此值强制为当前时间?
Is there some way to force this value to the current time on each admin site save?
也可以是否有某种方法可以添加 mod_count
字段,并在每次修改管理站点博客条目时自动计算该字段?
Also would there be some way to add a mod_count
field and have it automatically calculated on each modify of the admin site blog entry?
推荐答案
在模型中创建 DateTimeField
。每次保存时都要更新。这要求您使用 auto_now_add
选项:
Create a DateTimeField
in your model. Have it update whenever it is saved. This requires you to use the auto_now_add
option:
class DateTimeField([auto_now=False, auto_now_add=False, **options])
DateTimeField .auto_now_add¶
DateTimeField.auto_now_add¶
每次保存对象时自动将字段设置为现在。有用的
用于最后修改的时间戳。注意
始终使用当前日期。
不仅仅是
可以覆盖的默认值。
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.
它应该看起来像这样:
class Message(models.Model):
message = models.TextField()
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
< a href = http://docs.djangoproject.com/en/dev/ref/models/fields/ rel = nofollow noreferrer>模型字段引用
第二部分,我认为您必须重载
For the second part, I think you have to overload
ModelAdmin.save_model(self, request, obj, form, change)
如James Bennett所述此处。它看起来像这样:
As James Bennett describes here. It will look something like this:
class EntryAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if change:
obj.change_count += 1
obj.save()
这篇关于Django:模型上次修改日期和修改计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!