提问人:oakca 提问时间:11/10/2023 更新时间:11/13/2023 访问量:52
通过 sqlalchemy 创建自动增量列
Creating an autoincrement column via sqlalchemy
问:
我正在通过sqlalchemy orm使用Postgresql数据库。该表非常基本:
import sqlalchemy as sa
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Network(Base):
__tablename__ = 'networks'
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
name: Mapped[str] = mapped_column(sa.String(60))
type: Mapped[str] = mapped_column(sa.String(60))
version: Mapped[int] = mapped_column(sa.Integer)
我想将该列转换为检查是否存在相同和同一行的内容。如果是,则将前一个增加 1。version
name
type
version
因此,假设我的表已经有以下行:
id name type version
0 foo big 1
1 bar big 1
我在表中再插入一个,然后它应该是自动的:(foo, big)
id name type version
0 foo big 1
1 bar big 1
2 foo big 2
这样的事情可能吗?顺便说一句,如果不存在相同和相同,它也应该获得默认版本 1。name
type
答:
0赞
hmn Falahi
11/13/2023
#1
使用事件:before_insert
class Network(Base):
__tablename__ = 'networks'
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
name: Mapped[str] = mapped_column(sa.String(60))
type: Mapped[str] = mapped_column(sa.String(60))
version: Mapped[int] = mapped_column(sa.Integer)
def update_version(mapper, connection, target):
session = Session.object_session(target)
# Check if a row with the same name and type already exists
existing_row = session.query(Network.version) \
.filter(Network.name == target.name) \
.filter(Network.type==target.type) \
.order_by(Network.version.desc()) \
.first()
if existing_row:
# If it exists, increase the version by 1
target.version = existing_row.version + 1
else:
# If it doesn't exist, set the version to 1
target.version = 1
event.listen(Network, 'before_insert', update_version)
评论