Stefan
Stefan

Reputation: 12260

How to define two parent classes for SqlAlchemy entities?

Until now I have a parent class Entity for all my orm classes:

class AbstractEntity():  

    id = Column(Integer, primary_key=True) 

    @declared_attr
    def __tablename__(self):
        return AbstractEntity.table_name_for_class(self) 

    ...


Entity = declarative_base(cls=AbstractEntity)

class Drink(Entity):
    name = Entity.stringColumn()

I want my classes only to inherit from a single class Entity, not from a class Base and a mixin Entity. That works fine.

However, now I would like to introduce another parent class EntityAssociation that I can use as parent for all my asssociation classes that are used for many to many relationships, e.g.

class DrinkIngretients(EntityAssociation):
    drink_id = Entity.foreign_key(Drink)
    ingredient_id = Entity.foreign_key(Ingredient)
    ...

The class EntityAssociation should inherit from Base = declarative_base() but not from AbstractEntity. (It should not include the column id that is defined in AbstractEntity.)

=> How can I implement that inheritance structure?

I tried

class AbstractEntity():  

    id = Column(Integer, primary_key=True) 

    @declared_attr
    def __tablename__(self):
        return AbstractEntity.table_name_for_class(self) 

    ...

Base = declarative_base()

class Entity(Base, AbstractEntity):
    pass

class EntityAssociation(Base):
    pass

However, the behavior of

Entity = declarative_base(cls=AbstractEntity)

and

class Entity(Base, AbstractEntity):
    pass

seems to be different.

Class does not have a table or tablename specified and does not inherit from an existing table-mapped class.

=> How can I specify that the classes Entity and EntityAssociation should not have extra table names?

=> Any other suggestions on how to get the wanted inheritance structure?

Upvotes: 0

Views: 101

Answers (1)

Stefan
Stefan

Reputation: 12260

The __abstract__ flag did the trick:

class EntityRelation(Base):   
    __abstract__ = True

class Entity(Base, AbstractEntity): 
    __abstract__ = True

Upvotes: 0

Related Questions