Django 固定装置和 auto_now_add 日期时间字段

标签 django

尝试为具有 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.1Python 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/

相关文章:

python - xhtml2pdf 未正确转换 css django

django - 如何在 View 中包装 Django 表单向导?

python - 如何打印类属性/元素的文档字符串?

Python 导入错误 : No module named webpack_loader

django - 如何告诉 Django 模板不要解析包含看起来像模板标签的代码的 block ?

python - 为 Django 存档页面选择不同的年份和月份

python - 为我的 python 项目创建 setup.py,下载依赖包时出现问题

django - Python Django ValueError : source code string cannot contain null bytes

django - Django 1.8.13 的 TypeError,但 Django 1.9.6 没有

python - 表单返回奇怪的字符