Skip to content

Commit 5424182

Browse files
committed
Added automatic model loading
1 parent ae0c9c4 commit 5424182

2 files changed

Lines changed: 17 additions & 9 deletions

File tree

backend/app/alembic/env.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@
1919
# target_metadata = mymodel.Base.metadata
2020
# target_metadata = None
2121

22-
from app.models import SQLModel # noqa
22+
from app.constants import APP_PATH
23+
from importlib import import_module
24+
from sqlmodel import SQLModel
25+
for model_file in APP_PATH.glob("*/models.py"):
26+
import_module(f"app.{model_file.parent.name}.models")
27+
2328
from app.config import settings # noqa
2429

2530
target_metadata = SQLModel.metadata

backend/app/database.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,33 @@
1+
from importlib import import_module
2+
13
from sqlmodel import Session, create_engine, select
24

35
from app.config import settings
6+
from app.constants import APP_PATH
47
from app.users import service as user_service
58
from app.users.models import User
69
from app.users.schemas import UserCreate
710

811
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
912

1013

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")
1519

1620

1721
def init_db(session: Session) -> None:
1822
# Tables should be created with Alembic migrations
1923
# But if you don't want to use migrations, create
2024
# the tables un-commenting the next lines
21-
# from sqlmodel import SQLModel
25+
# from sqlmodel import SQLModel # noqa: ERA001
2226

2327
# 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
2629
user = session.exec(
27-
select(User).where(User.email == settings.FIRST_SUPERUSER)
30+
select(User).where(User.email == settings.FIRST_SUPERUSER),
2831
).first()
2932
if not user:
3033
user_in = UserCreate(

0 commit comments

Comments
 (0)