2016-11-21 73 views
2

使用SQLAlchemy 1.0.13,是否可以從繼承類中刪除relationship join使用繼承刪除SQLAlchemy關係

在下一個最小的工作示例中,我有一個父母和兩種孩子。子類與父類有關係。 AlienChild從Child獲取所有屬性,但我想放棄關係。這可能嗎?

class Parent(Base): 
    __tablename__ = 'parent' 
    id = Column(Integer, primary_key=True) 

class Child(Base): 
    __tablename__ = 'child' 
    id = Column(Integer, primary_key=True) 
    parent_id = Column(Integer, 
         ForeignKey('parent.id', 
         ondelete='CASCADE'), 
         nullable=False) 
    parent = relationship('Parent', 
        backref=backref(
         'children', cascade="all, delete-orphan"), 
        foreign_keys=[parent_id], 
        single_parent=True) 

class AlienChild(Child): 
    __tablename__ = 'alienchild' 
    parent = droprelationship('Parent') 

回答

1

從我的頭頂,我會嘗試的第一件事是

class AlienChild(Child): 
    __tablename__ = 'alienchild' 
    parent_id = None 
    parent = None 

,然而,從感覺來看OOP點有點奇怪。另外,如果不刪除其中一個類的關係,那麼backref可能會停止工作 - 它不能返回生活在不同表中的Child和AlienChild實例,它們彼此之間沒有任何關係。如果你想只在類之間共享一些功能,你可以使用混合類:

class Parent(Base): 
    __tablename__ = 'parent' 
    id = Column(Integer, primary_key=True) 

class PersonMixin: 
    id = Column(Integer, primary_key=True) 
    name = Column(String) 
    age = Column(Integer) 
    gender = Column(String) 

class HasParentMixin: 
    parent_id = Column(Integer, 
         ForeignKey('parent.id', 
         ondelete='CASCADE'), 
         nullable=False) 
    parent = relationship('Parent', 
        backref=backref(
         'children', cascade="all, delete-orphan"), 
        foreign_keys=[parent_id], 
        single_parent=True) 


class Child(Base, PersonMixin, HasPrentMixin): 
    __tablename__ = 'child' 


class AlienChild(Base, PersonMixin): 
    __tablename__ = 'alienchild'