Skip to content

Commit 101fc89

Browse files
committed
refactor: improve model imports for better alembic support
- Uses pathlib for traversing model paths to import for alembic. - Ensures subdirectory models are also imported automatically. Generated-by: aiautocommit
1 parent 73776d5 commit 101fc89

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

app/models/__init__.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
"""
2-
For alembic to properly pick up on all model metadata all models must be imported here
2+
For alembic to properly pick up on all model metadata all models must be imported here.
3+
4+
This imports all models in the current directory and subdirectories.
35
"""
46

57
import importlib
6-
import pkgutil
8+
from pathlib import Path
79

810
from app import log
9-
from app.setup import get_root_path
1011

11-
for _, module_name, _ in pkgutil.iter_modules([str(get_root_path() / "app/models")]):
12-
log.debug("auto importing", model=f"{__package__}.{module_name}")
13-
importlib.import_module(f"{__package__}.{module_name}")
12+
models_path = Path(__file__).parent
13+
14+
for py_file in models_path.rglob("*.py"):
15+
if py_file.name in ["__init__.py", "__main__.py"]:
16+
continue
17+
18+
rel_path = py_file.relative_to(models_path)
19+
module_parts = rel_path.with_suffix("").parts
20+
module_name = f"{__package__}." + ".".join(module_parts)
21+
log.debug("auto importing", model=module_name)
22+
importlib.import_module(module_name)

0 commit comments

Comments
 (0)