Home  >  Q&A  >  body text

python - 使用flask-migrate进行数据库迁移时,如何更改db.String()的长度?

比如有一个简单的模型

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True)

一开始,username的长度限制在32,现在将其增大,比如说变为128,flask-migrate似乎不会检测到这个String变长的变化。

我使用了命令自动生成迁移脚本

python code.py db migrate -m "some comment"
python code.py db upgrade

之后,发现username的列的长度依旧被限制在32.

如何进行String长度的变化这种迁移?

迷茫迷茫2742 days ago910

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 17:55:56

    alembic supports detecting field length changes, but it is not the default and needs to be configured.

    Settingscompare_typeTrue可以检查出类型字段的改变比如字段长度,设置compare_server_defaultYou can check out the changes to the default values ​​of the set fields.

    Detailed reference documentation

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:55:56

    flask-migrate will not detect column modifications, but you can do this
    First add a row under User, then migrate, then make modifications, delete the previously added rows, and then add a few more rows. Please note that It may not work under sqlite

    python code.py db edit

    def upgrade():
        ### commands auto generated by Alembic - please adjust! ###
        op.alter_column('users', 'username', existing_type=sa.String(32), type_=sa.String(128))
        ### end Alembic commands ###
    
    
    def downgrade():
        ### commands auto generated by Alembic - please adjust! ###
        op.alter_column('users', 'username', existing_type=sa.String(128), type_=sa.String(32))
        ### end Alembic commands ###
    

    Reference
    http://alembic.readthedocs.io/en/latest/ops.html

    reply
    0
  • Cancelreply