如何用Peewee/Playhouse Migrator添加带AFTER的列以定义表列顺序?
AFTER clause? Great question! The short answer is yes—you can add a column and specify its position using the AFTER clause with Peewee's Playhouse Migrator, but support depends entirely on your database system.
Supported Databases (MySQL)
MySQL natively supports the AFTER keyword to define column order when adding new columns. Playhouse's MySQLMigrator includes built-in support for this via the after parameter in the add_column method.
Example Code for MySQL
from peewee import MySQLDatabase from playhouse.migrate import MySQLMigrator, migrate # Set up your database connection db = MySQLDatabase( 'your_database_name', user='your_username', password='your_password', host='localhost' ) # Initialize the migrator migrator = MySQLMigrator(db) # Define your new column (adjust the type as needed) new_column = db.Column('your_table_name', 'new_column', 'VARCHAR(100) NOT NULL') # Run the migration, placing the new column after an existing one migrate( migrator.add_column( 'your_table_name', 'new_column', new_column, after='existing_column_to_follow' # Specify the column name here ) )
Unsupported Databases (PostgreSQL, SQLite)
PostgreSQL and SQLite do not support the AFTER clause for column ordering:
- PostgreSQL ignores column order entirely (it doesn't store or respect the order in queries unless explicitly specified).
- SQLite allows the syntax but doesn't actually enforce or store column order.
If you're using these databases, the after parameter will be silently ignored by their respective migrators (PostgresqlMigrator, SqliteMigrator). In most cases, this isn't a problem—column order rarely impacts application functionality, since you'll reference columns by name in your queries.
A Quick Note
Unless you have a specific requirement (like compatibility with an old system that relies on column order), it's generally not necessary to specify column position. Databases are designed to work with column names, not their physical order in the table.
内容的提问来源于stack exchange,提问作者ke4mtg

