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?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745645672a4637954.html
评论列表(0条)