【问题标题】:Drop SQLAlchemy relationship with inheritance删除 SQLAlchemy 与继承的关系
【发布时间】:2017-04-05 01:40:56
【问题描述】:

使用 SQLAlchemy 1.0.13,是否可以从继承类中删除 relationship join

在下一个最小的工作示例中,我有一个父母和两种类型的孩子。子类与父类有关系。 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')

【问题讨论】:

    标签: python-3.x sqlalchemy pyramid


    【解决方案1】:

    从我的脑海中,我会尝试的第一件事是

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

    然而,从 OOP 的角度来看,这感觉有点奇怪。此外,如果您不从其中一个类中删除关系,children backref 可能会停止工作 - 它无法返回位于不同表中且彼此没有任何关系的 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2016-04-29
      • 1970-01-01
      • 2010-11-23
      相关资源
      最近更新 更多