【问题标题】:Many-to-many relationship with different other objects, self and attributes in SQLAlchemy与 SQLAlchemy 中不同的其他对象、自身和属性的多对多关系
【发布时间】:2016-08-02 21:49:04
【问题描述】:

我用 SQLAlchemy 声明一个有点复杂的模型。我有基本的对象(在这种情况下字段并不重要):

class A(Base):
    __tablename__ = 'as'

class B(Base):
    __tablename__ = 'bs'

现在我想声明一个此类对象的集合,使用简单的relationship 很容易,但不幸的是,我需要followinf class C

  • 名为 members 的单个字段可以指向任意数量的 AB 对象
  • 它还需要能够包含对其他 C 对象的引用。
  • 映射需要附加一个属性。

我认为第三个要点很简单,如 http://pythoncentral.io/sqlalchemy-association-tables/ 所述。我不知道第一个是否可能,我不知道第二个。我尝试了一个简单的relationship('C'),但这导致 SQLAlchemy 抱怨很多关于重复外键字段的问题。

【问题讨论】:

    标签: python orm sqlalchemy


    【解决方案1】:

    答案是按照here 的描述使用连接表继承

    首先,为相似的类添加一个共同的父类,用一个名为 type(或其他任何东西)的字段作为鉴别器......

    class E(Base):
        __tablename__ = 'es'
        id = COlumn(Integer, primary_key=True)
        type = Column(String)
    

    …然后添加映射器参数:

        __mapper_args__ = {
            'polymorphic_identity': 'es',
            'polymorphic_on': type,
            'with_polymorphic': '*'
        }
    

    让相似的类继承自它……

    class A(E):
        __tablename__ = 'as'
    

    ...让他们使用共享的主键/外键和正确的映射器参数:

        id = Column(Integer, ForeignKey('es.id'), primary_key=True)
    
        __mapper_args__ = {
            'polymorphic_identity': 'as'
        }
    

    B 也是如此)

    然后可以定义与E 类的关系。

    如果你省略了 backref,那么与包含关系本身的类的关系就会起作用。

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 2015-03-16
      • 2018-11-24
      • 2023-03-10
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多