Separate SQLAlchemy models by file in Flask

PythonSqlalchemyFlaskFlask Sqlalchemy

Python Problem Overview


Many examples for Flask apps that I have seen have the models stored directly in the main app file (http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html, http://maximebf.com/blog/2012/10/building-websites-in-python-with-flask/). Other ones (http://flask.pocoo.org/docs/patterns/sqlalchemy/) have a "models.py" file in which models are placed.

How can I have my Flask app import models from separate files, e.x. "User.py"? When I try creating a User.py file with these contents:

from app import db

class User(db.Model):
    [...]

I get the following error:

File "/Users/stackoverflow/myapp/models/User.py", line 1, in <module>
from app import db
ImportError: No module named app

When I insert from models import User in my module file.

Python Solutions


Solution 1 - Python

This answer was extremely helpful: https://stackoverflow.com/a/9695045/353878.

I needed to not initialize the db right away.

Solution 2 - Python

from app.database import Base

class User(Base):
__tablename__ = 'users'

Shouldn it be this way ??

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionelement119View Question on Stackoverflow
Solution 1 - Pythonelement119View Answer on Stackoverflow
Solution 2 - PythonRedianView Answer on Stackoverflow