E.Bolandian
E.Bolandian

Reputation: 573

Add new column to exists table - Flask Sqlalchemy

I'm trying to add new column to exists table with data. The problem is that i dont know how to do it and i dont want to delete the whole table cause i already have data.

What should i do? how can i add another column without effect for bad my exists table

** This my table**

class Movies(db.Model):
__tablename__ = 'movies'
id = db.Column(db.String(300), primary_key=True, unique=True)
cat_id = db.Column(db.String(300), db.ForeignKey('category.id', ondelete='CASCADE'), nullable=False)
category = db.relationship('Category', backref='movies')
title = db.Column(db.String(250), nullable=False)
link = db.Column(db.String(250), nullable=False)
duration = db.Column(db.String(250), nullable=False)
thumb_large = db.Column(db.String(250), nullable=False)
thumb = db.Column(db.String(250), nullable=False)
embed = db.Column(db.String(250), nullable=False)
tags = db.Column(db.String(250), nullable=False)
published = db.Column(db.String(250), nullable=False)

Now i want to add new column which is video_id = db.Column(db.String(250)). The error that i get when i try to add it is [SQL: ALTER TABLE movies ADD COLUMN video_id VARCHAR(250) NOT NULL]

What should i do?

Upvotes: 0

Views: 1767

Answers (4)

Josie Koay
Josie Koay

Reputation: 831

You can refer alembic to solved this problem :)

However, here is how I solved :D

First, make sure you install

pip3 install alembic

Secondly, run alembic revision to create script. In my case, I run

python3 app.py db revision -m 'some message'

Third, run alembic upgrade head. For me, I run

python3 app.py db upgrade head

Lastly, I make changes in the script (without added this to script won't work for my case)

def upgrade():
    op.add_column('movies', sa.Column('video_id', sa.String())

def downgrade():
    op.drop_column('movies', 'video_id')

Upvotes: 1

E.Bolandian
E.Bolandian

Reputation: 573

Eventually what i did is i went to pgAdmin and added new column to the table, which is not the most correct way of doing it, but it worked.

Upvotes: 0

Vlad
Vlad

Reputation: 425

If you insert column in non empty table, video_id should be nullable=True. If it's not acceptable, you need to populate video_id by some data. For example:

video_id = db.Column(db.String(250), nullable=False, default='Some value here')

Upvotes: 2

Steffen Andersland
Steffen Andersland

Reputation: 609

There is a library that can help with managing database migrations. https://flask-migrate.readthedocs.io/en/latest/

But also, if you would like to avoiding an additional dependency and aren't afraid to break something you could run the raw SQL command that the error referencing.

ALTER TABLE movies ADD COLUMN video_id VARCHAR(250) NOT NULL

Upvotes: 1

Related Questions