【问题标题】:How to define two parent classes for SqlAlchemy entities?如何为 SqlAlchemy 实体定义两个父类?
【发布时间】:2019-10-29 00:47:16
【问题描述】:

到目前为止,我的所有 orm 类都有一个父类 Entity

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()

我希望我的类仅从单个类 Entity 继承,而不是从类 Base 和 mixin Entity 继承。效果很好。

但是,现在我想介绍另一个父类 EntityAssociation,我可以将它用作我所有用于多对多关系的关联类的父类,例如

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

EntityAssociation 类应该继承自 Base = declarative_base() 而不是继承自 AbstractEntity。 (它不应包括在AbstractEntity 中定义的列id。)

=> 如何实现该继承结构?

我试过了

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

然而,

的行为
Entity = declarative_base(cls=AbstractEntity)

class Entity(Base, AbstractEntity):
    pass

好像不一样。

类没有指定 tabletablename,也没有从现有的 table-mapped 类继承。

=> 如何指定 Entity 和 EntityAssociation 类不应有额外的表名?

=> 关于如何获得所需的继承结构还有其他建议吗?

【问题讨论】:

    标签: python inheritance orm sqlalchemy


    【解决方案1】:

    __abstract__ 标志成功了:

    class EntityRelation(Base):   
        __abstract__ = True
    
    class Entity(Base, AbstractEntity): 
        __abstract__ = True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2019-01-22
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多