Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

questions about the alembic. #61

Open
9ovn opened this issue Jan 2, 2025 · 3 comments
Open

questions about the alembic. #61

9ovn opened this issue Jan 2, 2025 · 3 comments

Comments

@9ovn
Copy link

9ovn commented Jan 2, 2025

If there's a models file inside each app as shown in the structure, how can I configure env.py or databases.py so that Alembic can detect all the tables in those models.py files? Currently, I'm manually importing each models file in env.py.

@zhanymkanov
Copy link
Owner

zhanymkanov commented Jan 2, 2025

With SQLAlchemy Core, I just store all models in database.py, and then use that metadata in alembic's env.py. Storing all models in one file is simple, because it doesn't require importing all models manually.

Separation by models.py in each module is for ORM-based apps.

@pydevup
Copy link

pydevup commented Jan 8, 2025

I created a models registry.
Created orm folder in src and inside it the __init__.py file imported all models.

__init__.py file:

from src.auth.models import User
from src.models import BaseModel

__all__ = ["BaseModel"]

and inside alembic env.py file:

from src.orm import BaseModel
target_metadata = BaseModel.metadata

@0-th
Copy link
Contributor

0-th commented Jan 8, 2025

I use a variant of the approaches in the previous responses, where I create a Base class with metadata in src/database.py:

from sqlalchemy import MetaData
metadata = MetaData(naming_convention=DB_NAMING_CONVENTION)

class Base(MappedAsDataclass, AsyncAttrs, DeclarativeBase):
    metadata = metadata

i use this Base in all my models.py then re-import from there into src/__init__.py:

from src.auth.models import Base as AuthBase
__all__ = ["AuthBase"]

this ensures the models in the imported models.py modules are registered.

then in alembic env.py module:

from src.database import metadata

target_metadata = metadata

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants