开发者

Must two SQLAlchemy declarative models share the same declarative_base()?

开发者 https://www.devze.com 2022-12-08 17:37 出处:网络
Is it necessary for two SQLAlchemy models to inherit from the same instance of declarative_base() if they must participate in the same Session? This is likely to be the case when importing two or more

Is it necessary for two SQLAlchemy models to inherit from the same instance of declarative_base() if they must participate in the same Session? This is likely to be the case when importing two or more modules that define SQLAlchemy models.

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))

Base2 = declarative_base()

class AnotherClass(Base2):
    __tablename__ 开发者_JAVA百科= 'another_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))


I successfully use different declarative bases in single session. This can be useful when using several databases: each base is created with own metadata and each metadata is bound to separate database. Some of your declarative bases could define additional methods or they could use another metaclass to install extensions.


Separate Base classes will work just fine.

You'll have to be careful when they are using different database connections, in that case you can't use joins across the two databases - every query needs to go to one database.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号