class Child(Model):
__tablename__ = 'child'
id = Column(Integer(), primary_key=True)
parent_id = Column(Integer(), ForeignKey('parent.id'))
# SELECT ... FROM parent WHERE parent.id = ?
parent = relationship(
'Parent',
back_populates='children',
# foreign_keys=[parent_id] # not required
)
def __repr__(self):
return '<Child {}>'.format(self.id)
class Parent(Model):
__tablename__ = 'parent'
id = Column(Integer(), primary_key=True)
# SELECT ... FROM child WHERE ? = child.parent_id
children = relationship(
'Child',
back_populates='parent',
cascade="all, delete-orphan",
# foreign_keys=[Child.parent_id] # not required
)
def __repr__(self):
return '<Parent {}>'.format(self.id)
显而易见,对于关系Parent.children来说,外键Child.parent_id是远程侧,使用Parent模型查询,会生成SELECT ... FROM child WHERE ? = child.parent_id这样的SQL语句
而对于关系Child.parent,外键Child.parent_id是本地侧,会生成SELECT ... FROM parent WHERE parent.id = ?查询语句。
自关联表
如果是自关联表,那么就是这样子:
class Node(Model):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
data = Column(String(50))
# SELECT ... FROM node WHERE ? = node.parent_id
children = relationship(
'Node',
back_populates='parent',
cascade='all',
# foreign_keys=[parent_id] # not required
)
# SELECT ... FROM node WHERE node.id = ?
parent = relationship('Node', back_populates='children', remote_side=[id])
# 等价于
# children = relationship(
# "Node",
# backref=backref('parent', remote_side=[id]),
# cascade='all',
# # lazy='dynamic',
# )
def __repr__(self):
return '<Node {}>'.format(self.id)
Node表有parent_id外键,对于Node.children来说,Node.parent_id是远程侧,调用时会生成SELECT ... FROM node WHERE ? = node.parent_id查询语句。
但是,对于关系Node.parent来说,按道理是在另一个模型里的,如果是在另一个模型会自动检测出来。但现在同一模型里面,所以如果不设置remote_side岂不是和Node.children一样?所以我们就要手动设置该关系函数的远程侧的字段,即Node.id。对应查询语句:SELECT ... FROM node WHERE node.id = ?