Django auto_now 行为

标签 django django-models

我有以下型号:

class MetaData(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by')
    updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
                                   related_name='%(app_label)s_%(class)s_updated_by')

update_at 字段也在创建时以一个值完成,而不是为空。我希望只有在第一次保存/创建之后才会有一个值。

我做错了吗?

最佳答案

在 Django 中,您有 auto_nowauto_now_add两者都有。

来自文档:

DateField.auto_now

Automatically set the field to now every time the object is saved. (which means when it is first created too)

DateField.auto_now_add

Automatically set the field to now when the object is first created.

编辑:

如果您希望在第一次创建对象时 updated_at 字段为 null,您只需将 null=Trueauto_now=TrueDateTimeField:

class MetaData(models.Model):
    # ...
    updated_at = models.DateTimeField(auto_now=True, null=True)
    # ...

关于Django auto_now 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45841270/

相关文章:

django - 将一个 Django 应用程序的模型重构为两个

python - 是否可以减少样板函数上的参数数量?

python - Django:有没有办法取消特定模型信号的接收器触发?

python - 通过字段名称映射接近 Django 模型字段

python - Django 奇怪的 SlugField 验证,在 clean() 之前未引发错误,返回未清理的数据

Django View 被调用两次(双 GET 请求)

django - 我可以轻松地覆盖 Django ORM 'iexact' 以使用 LOWER() 而不是 UPPER() 吗?

python - Django - "no module named django.core.management"

django - 在 git 项目中创建子模块

python - MacOS Sierra 后 Django 测试速度变慢