尝试为具有 auto_now_add
日期时间字段的模型创建固定装置
created_at = models.DateTimeField(auto_now_add=True)
加载灯具时会抛出错误IntegrityError:安装灯具时出现问题,“created_at”列中的空值违反了非空约束
有没有办法让 Django 确定日期而不是手动输入日期?
[
{
"model": "customer.type",
"pk": 1,
"fields": {
"name": "type",
"created_by": 1
}
}
]
最佳答案
简单的解决方法之一是使用 default
--[DjangoDoc]和 editable
--[DjangoDoc]一起争论,
<b>from django.utils import timezone</b>
class Foo(models.Model):
...
created_at = models.DateTimeField(<b>default=timezone.now, editable=False</b>)
上述解决方案在Django 2.1和Python 3.6环境下进行了测试和验证。
该方法的缺点
来自Django-Doc of DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of
auto_now_add=True
这意味着,如果您手动提供任何有效的日期时间,此设置将覆盖 timezone.now()
值。
关于Django 固定装置和 auto_now_add 日期时间字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546124/