【问题标题】:django.db.utils.IntegrityError: null value in column "id" violates not-null constraintdjango.db.utils.IntegrityError:“id”列中的空值违反非空约束
【发布时间】:2020-03-15 16:23:56
【问题描述】:

我想将 Django 模型中的数据保存到 PostgreSQL 数据库中:

mymodel.objects.create(title='test')

这个模型只有 title 和 id 但它会引发这个错误:

django.db.utils.IntegrityError:“id”列中的空值违反非空约束

我该如何解决?为什么 id 没有像往常一样自动设置?

【问题讨论】:

    标签: python django psql


    【解决方案1】:

    如果您以某种方式在数据库级别更改了您的 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
    

    参考号:Changing primary key int type to serial

    【讨论】:

      【解决方案2】:

      您应该允许 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

      【讨论】:

      • 我怎样才能让 Django 做到这一点?有没有我应该在 postgres 中运行的命令?
      • 如果你只把title字段放在你的模型中,Django会为你创建id并使其成为表的主键。我将在我的答案中添加一个示例。
      • 好吧,你是如何让 django 为表创建主键的?
      • 当你运行“python manage.py makemigrations”和“python manage.py migrate”时,将在Postgres中创建以“id”为主键的表。
      • 它在迁移时会引发同样的错误,并且不允许我运行这些错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2016-04-04
      • 2021-08-06
      • 2021-01-08
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多