5

是否可以在模型的添加/更改页面上允许手动编辑自动 DateTimeField。字段定义为:

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

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

4

2 回答 2

4

auto_now_add=Trueauto_now=True 假设 editable=False。因此,如果您需要更正此字段,请不要使用它们。

在 django 级别自动更新句柄。例如,如果您更新查询集,例如

Article.object.filter(pk=10).update(active=True)

不会更新post_updated字段。但

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

会做

于 2012-04-21T16:28:21.243 回答
1

auto_now_add=Trueauto_now=True假设editable=False。因此,如果您需要在 admin 或任何其他中修改此字段ModelForm,请不要使用这些auto_now_*=True设置。

这些字段的自动更新auto_now_*在 Django 级别处理。

如果您使用auto_now_*=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() 更新实例来实现,例如,

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
于 2014-03-24T21:56:50.953 回答