【发布时间】:2020-03-15 16:23:56
【问题描述】:
我想将 Django 模型中的数据保存到 PostgreSQL 数据库中:
mymodel.objects.create(title='test')
这个模型只有 title 和 id 但它会引发这个错误:
django.db.utils.IntegrityError:“id”列中的空值违反非空约束
我该如何解决?为什么 id 没有像往常一样自动设置?
【问题讨论】:
我想将 Django 模型中的数据保存到 PostgreSQL 数据库中:
mymodel.objects.create(title='test')
这个模型只有 title 和 id 但它会引发这个错误:
django.db.utils.IntegrityError:“id”列中的空值违反非空约束
我该如何解决?为什么 id 没有像往常一样自动设置?
【问题讨论】:
如果您以某种方式在数据库级别更改了您的 ID,并且您希望再次使其成为自动递增序列,请执行此操作
在下面的示例中,检查 mymodel 的表将在 Postgres 中在下面的示例中称为 mytable
Pick a starting value for the serial, greater than any existing value in the table
SELECT MAX(id)+1 FROM mytable
Create a sequence for the serial (tablename_columnname_seq is a good name)
CREATE SEQUENCE test_id_seq MINVALUE 3 (assuming you want to start at 3)
Alter the default of the column to use the sequence
ALTER TABLE test ALTER id SET DEFAULT nextval('test_id_seq')
Alter the sequence to be owned by the table/column;
ALTER SEQUENCE test_id_seq OWNED BY test.id
【讨论】:
您应该允许 Django 创建 id 作为主键,而不是显式地将其放入模型中。如果您需要将其作为单独的字段,您可以将其称为 mymodel_id 之类的其他名称。
例子:
class Book(models.Model):
title = models.CharField(null=False, blank=False)
def __str__(self):
return str(self.id)
运行之后:
python manage.py makemigrations
python manage.py migrate
如果您需要将 Django 与现有数据库集成,您可以试试这个:Integrating Django with an existing database
【讨论】: