简体   繁体   English

SQLAlchemy:如何向现有表添加列?

[英]SQLAlchemy: How to add column to existing table?

I am trying to add a field or column to an existing table using SQLAchemy.我正在尝试使用 SQLAchemy 将字段或列添加到现有表中。

Below is the table class下面是表类

class ReleaseVersion(Base):

    __tablename__ = 'versions'

    id = Column(Integer, primary_key=True, autoincrement=True)
    release = Column(String(128), nullable=False, unique=True)


    def __init__(self,release, id=None):

        if(id):
            self.id = id

        self.release = release

I initialized the table using following line我使用以下行初始化了表

myDB.ReleaseVersion.__table__.create(bind=self.engine, checkfirst=True)

After using the DB for some time, I need to add a boolean field, 'is_currentversion' while keeping all the existing content of the table, but I am not so sure how to do this.使用数据库一段时间后,我需要添加一个布尔字段“is_currentversion”,同时保留表的所有现有内容,但我不太确定如何执行此操作。

Should I manually create the field to the table an update the class?我应该手动为表创建字段并更新类吗? Alternatively, add the field in the table class and add column if it does not exist in the initialization function?或者,如果在初始化函数中不存在,则在表类中添加字段并添加列?

TL;DR TL; 博士

Install flask-migrate with pip or in your requirements.txt , then once you add your new column in your models:使用pip或在您的requirements.txt安装 flask-migrate ,然后在您的模型中添加新列后:

flask db init
flask db migrate -m "Adding column x."
flask db upgrade

Flask-Migrate烧瓶迁移

What you're looking for is called a database migration .您正在寻找的称为数据库迁移 Using something like Flask-Migrate allows you to change the database schema - adding or deleting columns - without losing your data.使用Flask-Migrate 之类的东西可以让你改变数据库模式——添加或删除列——而不会丢失你的数据。 It also versions these database migrations so you can revert back if necessary.它还对这些数据库迁移进行版本控制,因此您可以在必要时恢复。

Flask-Migrate uses the Alembic module so they both have the same functionality, Flask-Migrate is used to correctly setup alembic with your Flask and SQL-Alchemy application. Flask-Migrate 使用 Alembic 模块,因此它们都具有相同的功能,Flask-Migrate 用于在您的 Flask 和 SQL-Alchemy 应用程序中正确设置 Alembic。

If your app is pre-production:如果您的应用程序是预生产的:

Here is a great video by Pretty Printed for setting up Flask-Migrate.这是Pretty Printed用于设置 Flask-Migrate 的精彩视频。 Note that Flask-Migrate is intended for Flask applications that are using SQL-Alchemy as the ORM.请注意,Flask-Migrate 适用于使用 SQL-Alchemy 作为 ORM 的 Flask 应用程序。

If your app is post-production:如果您的应用是后期制作:

You have two options.你有两个选择。

  1. If you only want to track database migrations going forward (easier option)如果您只想跟踪未来的数据库迁移(更简单的选项)

Run flask db init , to create the migration repository.运行flask db init以创建迁移存储库。 Add the new column to your database model.将新列添加到您的数据库模型。

Run flask db migrate , to generate a migration.运行flask db migrate ,生成迁移。 The migration script will only have the new column in it.迁移脚本中将只包含新列。

Run flask db upgrade to apply the new migration to your database.运行flask db upgrade将新迁移应用到您的数据库。

At this point your database should have the new column, and you can continue working.此时您的数据库应该有新列,您可以继续工作。 Repeat the above steps any time you need to make additional changes.需要进行其他更改时,请随时重复上述步骤。

Note that with this approach, you cannot recreate the entire database from scratch.请注意,使用这种方法,您无法从头开始重新创建整个数据库。 You have to have a way to initialize the database to the schema you had on Day 1, and then you can apply the migration history to that to upgrade it to your current schema.您必须有一种方法将数据库初始化为您在第 1 天拥有的架构,然后您可以将迁移历史应用于该架构以将其升级到您当前的架构。

  1. If you want to keep track of the entire migration history, including the schema on the day you are adding Flask-Migrate to your application.如果您想跟踪整个迁移历史,包括将 Flask-Migrate 添加到应用程序当天的架构。

Start with flask db init , to create the migration repository.flask db init开始,创建迁移存储库。 Next, you need to trick Flask-Migrate into thinking your database is empty.接下来,您需要让 Flask-Migrate 认为您的数据库是空的。 You can do this by renaming your actual db, and creating a new db with the same name that has no tables in it.您可以通过重命名您的实际数据库,并创建一个同名的新数据库,其中没有表来做到这一点。

In that state, run flask db migrate .在该状态下,运行flask db migrate This will generate a migration that contains the entire schema of your database.这将生成一个包含整个数据库架构的迁移。 Once you have that initial migration, restore your database to the correct state.完成初始迁移后,将数据库恢复到正确状态。

Run flask db stamp head to mark the database as updated.运行flask db stamp head将数据库标记为已更新。 Add the new column to your database model.将新列添加到您的数据库模型。

Run flask db migrate again, to generate a second migration.再次运行flask db migrate以生成第二次迁移。 The migration script will only have the new column in it.迁移脚本中将只包含新列。

Run flask db upgrade to apply the new migration to your database.运行flask db upgrade将新迁移应用到您的数据库。

You can simply add a column in your model and then run the following commands.您可以简单地在模型中添加一列,然后运行以下命令。

flask db migrate -m "Your Message."

Then Run:然后运行:

flask db upgrade

Now check your database.现在检查您的数据库。 Also, you can take reference from Here另外,您可以从这里参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM