2016-11-21 9 views
2

SQLAlchemy 1.0.13では、継承クラスからrelationship joinを削除できますか?継承によるSQLAlchemy関係の削除

次に、私は親と2つのタイプの子を持っています。子クラスは親クラスとの関係を持ちます。 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

は、私がしようと最初にすることは、しかし、ビューのOOP点からちょっと奇妙な感じ

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

です。また、クラスの1つから関係を削除しないと、childrenバックリファレンスが機能しなくなる可能性があります。異なるテーブルに存在するChildとAlienChildのインスタンスを返すことはできません。クラス間でいくつかの機能だけを共有したい場合は、mixinクラスを使用できます:

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' 
関連する問題