![](/img/trans.png)
[英]Error when migrating: django.db.utils.IntegrityError: column "primary_language_id" contains null values
[英]Alembic: IntegrityError: “column contains null values” when adding non-nullable column
我正在向現有表添加列。 這個新列是nullable=False
。
op.add_column('mytable', sa.Column('mycolumn', sa.String(), nullable=False))
當我運行遷移時,它會抱怨:
sqlalchemy.exc.IntegrityError: column "mycolumn" contains null values
這是因為您的現有數據對該新列沒有任何價值,即null
。 從而導致所述錯誤。 添加不可為空的列時,必須確定為現有數據提供的值
好吧,現在的數據應該只有這個新專欄的“lorem ipsum”。 但是我該怎么辦呢? 我無法更新,因為該列還沒有。
使用server_default
arg:
op.add_column('mytable', sa.Column(
'mycolumn',
sa.String(),
nullable=False,
server_default='lorem ipsum', # <--- add this
))
但是,我不希望它具有默認值
之后使用op.alter_column('mytable', 'mycolumn', server_default=None)
刪除它
例如,您的upgrade()
函數將是:
def upgrade():
op.add_column('mytable', sa.Column('mycolumn', sa.String(), nullable=False, server_default='lorem ipsum'))
op.alter_column('mytable', 'mycolumn', server_default=None)
@ Ron的答案的另一種選擇是反過來,並在添加約束之前修改數據:
def upgrade():
op.add_column('my_table', sa.Column('my_column', sa.String()))
op.execute('UPDATE my_table SET my_column=my_other_column')
op.alter_column('my_table', 'my_column', nullable=False)
對我來說似乎更清潔,更強大,但你正在編寫SQL :-)。
它告訴您 - 正確地說 - 該列的數據庫中存在(或將存在)NULL值。 答案是在更改列定義之前編輯遷移文件以更新列:
from sqlalchemy.sql import table, column
def upgrade():
op.add_column('role', sa.Column('role_name', sa.String(length=30), nullable=True))
role = table('role', column('role_name'))
op.execute(role.update().values(role_name=''))
op.alter_column('role', 'role_name', nullable=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.