I'd like to use Flask-Migrate and am looking at their example:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
if __name__ == '__main__':
manager.run()
This works great as a simple play example, but I have more than a single model and I don't want to define the models in both this script and the one that defines my application code. Thus, I want to pull them into a model file that I can share between the two.
I attempting to do this, by placing the User
class into a models.py
and then importing User from there. Unfortunately, that throws a NameError: name 'db' is not defined
.
My question(s) are:
- Do I need to use
db = SQLAlchemy(app)
in mymodels.py
, and if so will this be available in both my migration script and the flask application itself? - If I can't (or shouldn't) put it in
models.py
, how do I utilize my models in their own file without passingdb
all over?