Question

I have a problem with class inheritance using SQLAlchemy.

The following min. example shows what I'd like to do and what my problem is:

class Foo(object):
    bar = 'hello world'

class Car(Base, Foo):
    id = Column(Integer, primary_key=True)
    color = Column(String(50))

if __name__ == '__main__':
    # 'bar' attribute is available on new class instance
    my_car = Car()
    print my_car.bar # "hello world"

    # 'bar' attribute is not available on query init
    db_session = init_db()
    my_car = db_session.query(Car).first()
    print my_car.bar # Error

I have a Car class which inherits from SQLAlchemy's Base class. In addition to that the Car class inheritates from a Foo class. In This example the Foo class just consists of an attribute bar.

When a Car instance is instanciated via SQLAlchemy's query function I can't access the bar attribute. How is SQLAlchemy instantiating classes and is there a workaround for me?

I'm using SQLAlchemy 0.7.

Was it helpful?

Solution

You can use cls parameter to declarative_base to replace default object as base for all your classes:

Base = declarative_base(cls=MyBaseClass)

For more information and options, please read Mixin and Custom Base Classes section of documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top