Skip to content

How can I save my model in another file? #1065

Answered by davidism
martinenkoEduard asked this question in Q&A
Discussion options

You must be logged in to vote

If your project looks like

project/
  app/
    __init__.py
    models.py

Then as long as you import the models after defining the db object, they will be registered with SQLAlchemy.

# __init__.py

app = Flask(__name__)
db = SQLAlchemy(app)
from . import models
# models.py

from . import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)

You can also use the app factory pattern to prevent causing circular import issues.

# __init__.py

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    from . import models
    return app

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@martinenkoEduard
Comment options

@martinenkoEduard
Comment options

@ThiefMaster
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by davidism
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants