SQLAlchemy One-to-Many relationship on single table inheritance - declarative

后端 未结 1 517
夕颜
夕颜 2020-12-16 00:01

Basically, I have this model, where I mapped in a single table a \"BaseNode\" class, and two subclasses. The point is that I need one of the subclasses, to have a one-to-man

相关标签:
1条回答
  • I was struggling through this myself earlier. I was able to get this self-referential relationship working:

    class Employee(Base):
      __tablename__ = 'employee'
      id = Column(Integer, primary_key=True)
      name = Column(String(64), nullable=False)
    Employee.manager_id = Column(Integer, ForeignKey(Employee.id))
    Employee.manager = relationship(Employee, backref='subordinates',
        remote_side=Employee.id)
    

    Note that the manager and manager_id are "monkey-patched" because you cannot make self-references within a class definition.

    So in your example, I would guess this:

    class NodeTypeA(BaseNode):
        __mapper_args__ = {'polymorphic_identity': 'NodeTypeA'}
        typeB_children = relationship('NodeTypeB', backref='parent_node',
            remote_side='NodeTypeB.parent_id')
    

    EDIT: Basically what your error is telling you is that the relationship and its backref are both identical. So whatever rules that SA is applying to figure out what the table-level relationships are, they don't jive with the information you are providing.

    I learned that simply saying mycolumn=relationship(OtherTable) in your declarative class will result in mycolumn being a list, assuming that SA can detect an unambiguous relationship. So if you really want an object to have a link to its parent, rather than its children, you can define parent=relationship(OtherTable, backref='children', remote_side=OtherTable.id) in the child table. That defines both directions of the parent-child relationship.

    0 讨论(0)
提交回复
热议问题