How can I migrate a table with data in a table which got a new datetime column which is non-nullable?

邮差的信 提交于 2019-12-24 19:25:15

问题


I've added a column

registered_on = db.Column(db.DateTime, nullable=False)

to my users table. The migration which was automatically created is

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    ...
    op.add_column('users', sa.Column('registered_on', sa.DateTime(), nullable=False))
    ...

When I execute it, I got an exception about an invalid value 0000-00-00 00:00:00 (or so).

How should I adjust the migration script to not have this problem?

(In this situation, filling in a dummy value would probably have been the best)


回答1:


I can think of two ways to do this:

  1. Add a server_default to the add_column operation:
op.add_column('users', sa.Column('registered_on', sa.DateTime(), nullable=False, server_default=func.now()))
  1. First insert the column as nullable, then edit all your rows to have a value. Once all the rows have been given a non-null value, do another migration to alter the column to non-nullable.


来源:https://stackoverflow.com/questions/56712645/how-can-i-migrate-a-table-with-data-in-a-table-which-got-a-new-datetime-column-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!