SQLALCHEMY采用adjacency list pattern来表示类的自引用。

例如,对于类Node自引用:

class Node(Base):
    __tablename__='node'
    id=Column(Integer,primary_key=True)
    parent_id=Column(Integer,ForeignKey('node.id'))
   data=Column(String(50))
    children=relationship('Node')

对于如下图所示的结构:

root--------------->child1

-------->child2---------->subchild1

---------->subchild2

-------->child3

可能有如下数据:

id parent_id data

1 NULL root

2 1 child1

3 1 child2

4 3 subchild1

5 3 subchild2

6 1 child3

无论自引用是一对多还是多对一,通常默认是一对多。如果想建立多对一的关系,需要在relationship()中添加remote_side属性,remote_side属性包含一列或多列。如:

class Node(Base):
    __tablename__='node'
    id=Column(Integer,primary_key=True)
    parent_id=Column(Integer,ForeignKey('node.id'))
    data=Column(String(50))
    parent=relationship("Node",remote_side=[id])

 

相关文章:

  • 2021-08-16
  • 2022-12-23
  • 2022-01-05
  • 2021-12-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
猜你喜欢
  • 2021-07-08
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-01-25
  • 2022-12-23
  • 2021-11-08
相关资源
相似解决方案