Conor Jalen
Conor Jalen

Reputation: 61

How to add column to existing Table? in Flask SqlAlchemy

I have a flask SqlAclchemy table called User:

class User(db.Model):
    id = db.Column(db.INTEGER, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)

i have now edited it and added this line;favCol = db.Column(db.String(12))

how do i update the table for it to recognize this new colum when i add a new user? At the moment when i create a User like User(username="bob",favCol="red") it gives me an error:

TypeError: 'favCol' is an invalid keyword argument for User

I have heard of solution with Migrate although i would prefer re a simpler solution if possible

Upvotes: 4

Views: 5617

Answers (2)

DarkGoldBar
DarkGoldBar

Reputation: 1

This answer will help:
https://stackoverflow.com/a/17243132/19280304

For flask-SQLAlchemy, add this before the code

from flask_sqlalchemy import SQLAlchemy
engine  = SQLAlchemy(app).engine

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 880

If you don't care about the data in the database getting erased. You can do the following:

from terminal if 'py' doesn't start python, try 'python'. press enter after each of these commands

py
from projectdirectory import db
db.drop_all()
db.create_all()

If you care about your existing data, you need to use something like flask_migrate which uses alembic in order to help you do database migrations while maintaining your data.

Upvotes: 1

Related Questions