sqlalchemy 各种关系的写法

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里写ForeignKeyparent的主键,child里写relationshipparent里同样写relationshipback_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")

中间表里写上parentchild的主键作为foreignkeyparentchild里的relationship加入参数secondary,指定为中间表。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

sql注入

反引号是个比较特别的字符,下面记录下怎么利用0x00SQL注入反引号可利用在分隔符及注释作用,不过使用范围只于表名、数据库名、字段名、起别名这些场景,下面具体说下1)表名payload:select\from\users\whereuser\_id1limit0,1;!(https://o