是否可以在模型的添加/更改页面上手动编辑自动日期时间字段。该字段定义为:Django admin - 允许手动编辑自动日期时间字段
post_date = models.DateTimeField(auto_now_add=True)
post_updated = models.DateTimeField(auto_now=True)
我不知道如何手动中重写这些将工作完全是在数据库级别或在Django本身处理的自动更新?
是否可以在模型的添加/更改页面上手动编辑自动日期时间字段。该字段定义为:Django admin - 允许手动编辑自动日期时间字段
post_date = models.DateTimeField(auto_now_add=True)
post_updated = models.DateTimeField(auto_now=True)
我不知道如何手动中重写这些将工作完全是在数据库级别或在Django本身处理的自动更新?
auto_now_add=True
和auto_now=True
assumeeditable=False
。所以如果你需要纠正这个领域,不要使用它们。
在django级别自动更新句柄。例如,如果你更新了queryset,例如
Article.object.filter(pk=10).update(active=True)
不会更新post_updated
字段。但
article = Article.object.get(pk=10)
article.active = True
atricle.save()
会做
auto_now_add=True
和auto_now=True
承担editable=False
。因此,如果您需要在管理员或其他任何ModelForm
中修改此字段,请不要使用auto_now_*=True
设置。
自动更新这些auto_now_*
字段在Django级别处理。
如果更新与auto_now_*=True
领域模型的实例,那么Django会自动如果要覆盖在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
,你可以这样做的通过queryset.update()更新实例,例如:
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
自动更新在Django级别的'DateTimeField'的'pre_save'方法中处理。 – okm 2012-04-21 16:30:41
一切皆有可能,但如果您能告诉我们您希望这些字段的行为如何,它可能会更容易。我认为''post_date''字段使用'default = datetime.datetime.now'会更好,并且可以在** Form **中调整post_updated字段的初始值。 – seler 2012-04-21 18:45:54