Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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__ = 'another_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))
like image 492
joeforker Avatar asked Oct 19 '09 16:10

joeforker


2 Answers

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.

like image 139
Denis Otkidach Avatar answered Nov 07 '22 07:11

Denis Otkidach


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.

like image 23
Ants Aasma Avatar answered Nov 07 '22 08:11

Ants Aasma