Django admin-允许手动编辑自动日期时间字段

Django admin-允许手动编辑自动日期时间字段,django,django-admin,Django,Django Admin,是否可以在模型的添加/更改页面上手动编辑自动日期时间字段。这些字段定义为: post_date = models.DateTimeField(auto_now_add=True) post_updated = models.DateTimeField(auto_now=True) 我不确定手动覆盖这些将如何工作,自动更新是在数据库级别处理还是在django本身处理?auto\u now\u add=True和auto\u now=Trueeditable=False。因此,如果您需要更正此字段

是否可以在模型的添加/更改页面上手动编辑自动日期时间字段。这些字段定义为:

post_date = models.DateTimeField(auto_now_add=True)
post_updated = models.DateTimeField(auto_now=True)

我不确定手动覆盖这些将如何工作,自动更新是在数据库级别处理还是在django本身处理?

auto\u now\u add=True
auto\u now=True
editable=False
。因此,如果您需要更正此字段,请不要使用它们

自动更新django级别的句柄。例如,如果您更新queryset,例如

Article.object.filter(pk=10).update(active=True)
不会更新
post\u updated
字段。但是

article = Article.object.get(pk=10)
article.active = True
atricle.save()

将执行
auto\u now\u add=True
auto\u now=True
假设
editable=False
。因此,如果您需要在admin或任何其他
ModelForm
中修改此字段,则不要使用
auto\u now.*=True
设置

这些
auto\u now.*
字段的自动更新在Django级别处理

如果使用
auto\u now\u*=True
字段更新模型实例,Django将自动更新该字段,例如

class Article(models.Model):
    active = models.BooleanField()
    updated = models.DateTimeField(auto_now=True)
article = Article.object.get(pk=10)
article.active = True
article.save()
# ASSERT: article.updated has been automatically updated with the current date and time
如果要在Django中重写此自动行为,可以通过queryset.update()更新实例,例如


自动更新在Django级别的
DateTimeField
pre_save
方法中处理。一切都是可能的,但如果您能告诉我们您希望这些字段的具体行为,则会更容易。我认为最好使用
default=datetime.datetime.now
作为
post\u date
字段,并在表单中调整
post\u updated
字段的初始值。
Article.object.filter(pk=10).update(active=True)
# ASSERT: Article.object.get(pk=10).updated is unchanged

import datetime
Article.object.filter(pk=10).update(updated=datetime.datetime(year=2014, month=3, day=21))
# ASSERT: article.updated == March 21, 2014