Django DateTimeField "auto_now" 似乎不起作用

Django's DateTimeField's "auto_now" doesn't seem to work

我有一个 Comment 模型。它具有以下时间戳字段:

created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_edit = models.DateTimeField(auto_now=True, blank=True, null=True)

现在,当我使用此格式更新评论时:Comment.objects.filter(...).update(text="some new text")last_edit 字段不会更新,而评论文本会更新。有什么问题?

更新:此外,我正在使用 filter,因为 update 不适用于 get,即 Comment.objects.get(...).update(...) 无效。我真正想做的是 get 因为我确定一次只能更新一条评论。

因为您使用的是 update,它直接在数据库中进行更新,而 auto_now 是在 Python 中完成的。这会起作用:

for commment in Comment.objects.filter(...):
    comment.text="some new text"
    comment.save()

显然,这比在数据库中一次性完成效率低。如果您真的需要,那么您还必须在更新中设置日期:

Comment.objects.filter(...).update(text="some new text", last_edit=datetime.datetime.now())