python - What are the conventions around abstract base hierarchy in SQLAlchemy 2.0? - Stack Overflow

In SQLAlchemy 2.0, I understand that the __abstract__ flag can be used to create abstract base classes

In SQLAlchemy 2.0, I understand that the __abstract__ flag can be used to create abstract base classes that don’t map to a table themselves but can be inherited by other classes to create actual mapped tables. I also know that the metadata object can be used to anize tables and control which schema or database they belong to.

From the docs:

class Base(DeclarativeBase):
    pass


class DefaultBase(Base):
    __abstract__ = True
    metadata = MetaData()


class OtherBase(Base):
    __abstract__ = True
    metadata = MetaData()

Above, classes which inherit from DefaultBase will use one MetaData as the registry of tables, and those which inherit from OtherBase will use a different one. The tables themselves can then be created perhaps within distinct databases.

I am curious as to when the above approach should be preferred over creating two indepenent abstract bases inherited directly from DeclarativeBase.

class Base1(DeclarativeBase):
    __abstract__ = True
    metadata = MetaData()

class Base2(DeclarativeBase):
    __abstract__ = True
    metadata = MetaData()

I understand programmatically the two approaches are, in practice identical unless the common Base were to define some behaviour or attributes to be shared among the two inherited abstract bases. Is there anything more that one should probably consider?

The second part to this question is around the usage of the __abstract__ attribute itself. The docs state:

__abstract__ causes declarative to skip the production of a table or mapper for the class entirely.

When it comes to Base classes as the above, what exactly does abstract change? If I understand correctly, no mapping is created unless a class subclasses the Base and defines columns and the __tablename__? So is there an actual restriction __abstract__ is enforcing here?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745645672a4637954.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信