Intro
因为 sqlalchemy 这玩意儿不是特别常用,偶然提起的时候想写个多对多关系还搜索了半天。于是趁机做个笔记。
注意事项
ForeignKey
db.ForeginKey的参数是<表名>.<键名>,而不是<类名>.<字段名>,务必注意这个区别。
back_populates 和 backref 在多对多关系中使用的区别
back_populates是更推荐的写法。
多对多关系中使用backref并指定了secondary的话,另一张表关联的relationship字段会使用相同的secondary。
back_populates则需要在两张表的relationship中都写上相同的secondary中间表。
可调用的 secondary
secondary参数可以是一个可调用对象,做一些 trick 的时候应该有用。姑且记下。
一对多关系
1class Parent(Base): 2 __tablename__ = 'parent' 3 id = Column(Integer, primary_key=True) 4 child = relationship("Child", back_populates="parent") 5 6class Child(Base): 7 __tablename__ = 'child' 8 id = Column(Integer, primary_key=True) 9 parent_id = Column(Integer, ForeignKey('parent.id')) 10 parent = relationship("Parent", back_populates="child")
parent包含多个child的一对多关系。child里写ForeignKey为parent的主键,child里写relationship,parent里同样写relationship,back_populates填充上,完事。
一对一关系
1class Parent(Base): 2 __tablename__ = 'parent' 3 id = Column(Integer, primary_key=True) 4 child = relationship("Child", uselist=False, back_populates="parent") 5 6class Child(Base): 7 __tablename__ = 'child' 8 id = Column(Integer, primary_key=True) 9 parent_id = Column(Integer, ForeignKey('parent.id')) 10 parent = relationship("Parent", back_populates="child")
一对一关系中parent需要在relationship里加入参数uselist,其他相同,完事儿。
多对多关系
多对多关系需要一个中间表。
1association_table = Table('association', Base.metadata, 2 Column('left_id', Integer, ForeignKey('left.id')), 3 Column('right_id', Integer, ForeignKey('right.id')) 4) 5 6class Parent(Base): 7 __tablename__ = 'left' 8 id = Column(Integer, primary_key=True) 9 children = relationship( 10 "Child", 11 secondary=association_table, 12 back_populates="parents") 13 14class Child(Base): 15 __tablename__ = 'right' 16 id = Column(Integer, primary_key=True) 17 parents = relationship( 18 "Parent", 19 secondary=association_table, 20 back_populates="children")
中间表里写上parent和child的主键作为foreignkey,parent和child里的relationship加入参数secondary,指定为中间表。