簡體   English   中英

django.db.utils.IntegrityError:“id”列中的 null 值違反非空約束

[英]django.db.utils.IntegrityError: null value in column “id” violates not-null constraint

我想將 Django model 數據庫中的數據保存到 PostgreSQL 數據庫中:

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

這個 model 只有 title 和 id 但它會引發這個錯誤:

django.db.utils.IntegrityError:“id”列中的 null 值違反非空約束

我該如何解決? 為什么 id 沒有像往常一樣自動設置?

您應該允許 Django 創建 id 作為主鍵,而不是顯式地將其放入 model 中。 如果您需要將其作為單獨的字段,您可以將其稱為 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

如果您以某種方式在數據庫級別更改了您的 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

REF: 將主鍵 int 類型更改為串行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM