0

I'm new with flask-migrate (and so with Python...) but I'll get to the point.

I used to store all of my models inside a single models.py file but then I decided to separate every model to its corresponding file.

After reading this question. I assumed this would be a quick way for Flask-Migrate (or Alembric) to know all modules within the models package. So I did that way, but once I tried the flask db migrate command, the generated migration file simply dropped a few tables but not all of them.

Here's the project structure:

├── app/
│   ├── __init__.py
│   └── api/
│       ├── __init__.py
│       ├── models/
│       │   ├── __init__.py
│       │   ├── model1.py
│       │   └── model2.py
│       ├── resources/
│       └── schemas/
└── run.py

run.py

from app import create_app

app = create_app()
app.run(port=5000)

app/__init__.py

from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)

    db.init_app(app)
    migrate.init_app(app, db)

    # importing the models...
    from .api import models # this should work?
    # ... or do I have to manually write every single module?

    return app

app/api/models/__init__.py

from os.path import dirname, basename, isfile, join
import glob

# Trying to apply what I learned from the referenced question...
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [
    basename(f)[:-3] for f in modules if isfile(f) and not f.endswith("__init__.py")
]

Model files in app/api/models/

from app import db

class ExampleModel(db.Model):
    # Model declarations goes here...
    pass

So... to summarize this question, is there a better way to do this or I should import every single module in the app/__init__.py file?

Ex7
  • 11
  • 1
  • 3
  • The `models/__init__.py` isn't importing any models, it just puts their names in `__all__`. I think all that's missing in your solution is actually importing the model classes in that file. – Miguel Grinberg Jun 07 '21 at 07:56
  • Thank you for your comment. You're right, I missed importing the rest of the modules inside the `models/__init__.py` file. All I needed was a simple `from . import *`. – Ex7 Jun 09 '21 at 19:04

0 Answers0