views:

233

answers:

2

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))
+1  A: 

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.

Ants Aasma
+2  A: 

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.

Denis Otkidach
You can also use a single Session with the binds={Class:database,...} argument.
joeforker
Sure. But such binds dictionary is hard to maintain when it become huge. While I say about constructing it automatically from several metadata objects.
Denis Otkidach