且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在多主键表中插入具有自动递增ID的行?

更新时间:2023-11-24 13:35:46

在列定义上使用默认值

id = Column(Integer, default = sqlexpression)

其中sqlexpression可以是sql表达式。这是文档 。对于自动增量,您应该使用SQL表达式 coalesce(从order,0中选择max(order.id)+ 1 。为简便起见,您可以导入sqlalchemy.sql.text,以便id列看起来像

Where sqlexpression can be a sql expression. Here is the documentation. For autoincrement you should use the sql expression coalesce(select max(order.id) from order,0) + 1. For ease you could import sqlalchemy.sql.text so the id column could look something like

id = Column(Integer, default = text("coalesce(select max(order.id) from order,0) + 1"))