|
| 1 | +from importlib import import_module |
| 2 | + |
1 | 3 | from sqlmodel import Session, create_engine, select |
2 | 4 |
|
3 | 5 | from app.config import settings |
| 6 | +from app.constants import APP_PATH |
4 | 7 | from app.users import service as user_service |
5 | 8 | from app.users.models import User |
6 | 9 | from app.users.schemas import UserCreate |
7 | 10 |
|
8 | 11 | engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI)) |
9 | 12 |
|
10 | 13 |
|
11 | | -# make sure all SQLModel models are imported (app.models) before initializing DB |
12 | | -# otherwise, SQLModel might fail to initialize relationships properly |
13 | | -# for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28 |
14 | | -import app.models # noqa: E402, F401 # pyright: ignore[reportUnusedImport] |
| 14 | +# make sure all SQLModel models are imported before initializing DB otherwise, SQLModel |
| 15 | +# might fail to initialize relationships properly |
| 16 | +# for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28\ |
| 17 | +for model_file in APP_PATH.glob("*/models.py"): |
| 18 | + import_module(f"app.{model_file.parent.name}.models") |
15 | 19 |
|
16 | 20 |
|
17 | 21 | def init_db(session: Session) -> None: |
18 | 22 | # Tables should be created with Alembic migrations |
19 | 23 | # But if you don't want to use migrations, create |
20 | 24 | # the tables un-commenting the next lines |
21 | | - # from sqlmodel import SQLModel |
| 25 | + # from sqlmodel import SQLModel # noqa: ERA001 |
22 | 26 |
|
23 | 27 | # This works because the models are already imported and registered from app.models |
24 | | - # SQLModel.metadata.create_all(engine) |
25 | | - |
| 28 | + # SQLModel.metadata.create_all(engine) # noqa: ERA001 |
26 | 29 | user = session.exec( |
27 | | - select(User).where(User.email == settings.FIRST_SUPERUSER) |
| 30 | + select(User).where(User.email == settings.FIRST_SUPERUSER), |
28 | 31 | ).first() |
29 | 32 | if not user: |
30 | 33 | user_in = UserCreate( |
|
0 commit comments