admin管理员组文章数量:1435090
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 oneMetaData
as the registry of tables, and those which inherit fromOtherBase
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?
本文标签: pythonWhat are the conventions around abstract base hierarchy in SQLAlchemy 20Stack Overflow
版权声明:本文标题:python - What are the conventions around abstract base hierarchy in SQLAlchemy 2.0? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745645671a2668119.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论