Reputation: 395
I am making a simple web application using sqlite as my database with the help of flask-sqlalchemy. After creating the application, I realise I need to add a new column to the database. However, when I modify the models.py file directly, they say the new column is not available as the error.
My understanding is this is probably because the database has already been created so I am unable to edit the models.py directly. May I know what I can do to add the 'photo' column in the database? Should I delete the current data base file (db.sqlite) and create the tables again?
Here's the models.py file currently:
1 from flask_login import UserMixin
2 from . import db
3
4 class User(UserMixin, db.Model):
5 __tablename__ = "user"
6 __table_args__ = {'extend_existing': True}
7
8 id = db.Column(db.Integer, primary_key=True)
9 email = db.Column(db.String(100), unique=True)
10 password = db.Column(db.String(100))
11 name = db.Column(db.String(1000))
12
13 class Item(UserMixin, db.Model):
14 __tablename__ = "item"
15 __table_args__ = {'extend_existing': True}
16
17 id = db.Column(db.Integer, primary_key=True)
18 item = db.Column(db.String(100), nullable=False)
19 description = db.Column(db.String(1000), nullable=False)
20 occurdate = db.Column(db.Date)
21 time = db.Column(db.Time)
22 # photo = db.Column(db.LargeBinary)
Upvotes: 2
Views: 1617
Reputation: 13120
When you have a SQL database and you want to make changes to the schema of an existing database, you basically have three options:
These are tools that migrate the database for you, usually by versioning each iteration of the database and using scripts that migrate the database between versions. Alembic is the officially supported tool for SQLAlchemy and generally recommended by a lot of users.
If you don't want the hassle of using a tool, you can connect directly to your database (for example by using the sqlite command line tool) and running alter table
commands. This is what a migration tool automates for you, but if you want to keep it simple and interact directly with your database, using alter table
commands is usually pretty simple.
You can also of course just delete your database and start from scratch.
Often, when you're just prototyping a project and you haven't made a lot of progress yet on deciding on how you want your tables laid out, this is the best approach.
Once you have real data in a production database, however, this isn't an option so it's probably worthwhile to familiarize yourself with the first two methods either way.
Upvotes: 4