Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add column to SQLAlchemy Table

I made a table using SQLAlchemy and forgot to add a column. I basically want to do this:

users.addColumn('user_id', ForeignKey('users.user_id')) 

What's the syntax for this? I couldn't find it in the docs.

like image 943
Chris Avatar asked Sep 04 '11 17:09

Chris


People also ask

How do I add a column to an existing table in flask?

Run flask db migrate , to generate a migration. The migration script will only have the new column in it. Run flask db upgrade to apply the new migration to your database. At this point your database should have the new column, and you can continue working.

How do I add a column to an existing table in MySQL?

The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name.


2 Answers

I have the same problem, and a thought of using migration library only for this trivial thing makes me
tremble. Anyway, this is my attempt so far:

def add_column(engine, table_name, column):     column_name = column.compile(dialect=engine.dialect)     column_type = column.type.compile(engine.dialect)     engine.execute('ALTER TABLE %s ADD COLUMN %s %s' % (table_name, column_name, column_type))  column = Column('new_column_name', String(100), primary_key=True) add_column(engine, table_name, column) 

Still, I don't know how to insert primary_key=True into raw SQL request.

like image 120
AlexP Avatar answered Oct 02 '22 09:10

AlexP


This is referred to as database migration (SQLAlchemy doesn't support migration out of the box). You can look at using sqlalchemy-migrate to help in these kinds of situations, or you can just ALTER TABLE through your chosen database's command line utility,

like image 23
Demian Brecht Avatar answered Oct 02 '22 09:10

Demian Brecht