最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin5PV0评论

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?

Post a comment

comment list (0)

  1. No comments so far