SQLAlchemy中与关联代理的自引用多对多关系

时间:2018-12-08 01:36:58

标签: python sql sqlalchemy many-to-many

我正在尝试创建自参考多对多关系。 SQLAlchemy documentation中概述的示例非常有用。这是我创建的模型:

from sqlalchemy import Integer, ForeignKey, String, Column, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

Table('NodeToNode', Base.metadata,
    Column('leftNodeId', Integer, ForeignKey('Node.id'), primary_key=True),
    Column('rightNodeId', Integer, ForeignKey('Node.id'), primary_key=True)
)

class Node(Base):
    __tablename__ = 'Node'
    id = Column(Integer, primary_key=True)
    label = Column(String)

    rightNodes = relationship('Node',
        secondary='NodeToNode',
        primaryjoin='Node.id==NodeToNode.c.leftNodeId',
        secondaryjoin='Node.id==NodeToNode.c.rightNodeId',
        backref='leftNodes'
    )

以及用于在其中添加数据的脚本:

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

engine = create_engine('sqlite:///practice.sqlite3')
session = Session(bind=engine)

nodes = [
    Node(label='A'),
    Node(label='B'),
    Node(label='C'),
    Node(label='D'),
    Node(label='E'),
]

nodes[0].rightNodes = [nodes[1], nodes[3], nodes[2]]
nodes[0].leftNodes = [nodes[4]]

session.add_all(nodes)
session.commit()

我想在关联表中添加一列,所以我假设我需要将关联表转换为其自己的类:

class NodeToNode(Base):
    __tablename__ = 'NodeToNode'
    leftNodeId = Column(Integer, ForeignKey('Node.id', onupdate='CASCADE'), primary_key=True)
    rightNodeId = Column(Integer, ForeignKey('Node.id', onupdate='CASCADE'), primary_key=True)
    sortOrder = Column(Integer, nullable=False)

但是,这导致以下错误:

sqlalchemy.exc.InvalidRequestError: Class <class 'models.node.NodeToNode'> does not have a mapped column named 'c'

知道我在做什么错吗?

0 个答案:

没有答案