Chris McKinnel
Chris McKinnel

Reputation: 15082

Structure of a Flask app with more than one models.py

I currently have a Flask app with the following structure:

deploy/
api/
  customer/
    models.py
  contact/
    models.py
  campaign/
    models.py
  activity/
    models.py
  __init__.py
  database.py
tests/
  test_api.py

Because I have so many models, I have split them out into separate files which is causing me issues when I try and initialise my DB.

In each one of my models, I do the following to make Flask-SQLAlchemy's Model call available:

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class User(db.Model):
...

Doing it this way means there's a different db object for every model which makes it impossible to initialise my app properly.

How can I structure my project so I can have one db object that is used by all my models, tests and my create_app() function in __init__.py?

Upvotes: 3

Views: 1031

Answers (1)

DazWorrall
DazWorrall

Reputation: 14210

Here's one way:

  myapp/
    __init__.py
    database.py
    app.py
    model1/
      __init__.py
      models.py
    model2/
      __init__.py
      models.py

In the database.py:

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

In the various models.py files:

from ..database import db

class User(db.Model):
    ...

This makes use of explicit relative imports

Upvotes: 4

Related Questions