【发布时间】:2021-07-02 12:16:25
【问题描述】:
我希望我的所有对象都有一个由 PostgreSQL 设置的唯一 id,带有一个(序列)和另一个取决于第一个的 id。 创建对象时,如果我在保存后设置第二个 id,我将在表上有一个 INSERT 和一个 UPDATE,这并不是最好的。 所以只有一个 INSERT 我从 PostgreSQL 序列中获取 id 并用它设置 id 而不是让 PostgreSQL 在 INSERT 阶段执行它。 我是 SQLAlchemy 的新手,我想确保这种做法是竞争条件证明。
感谢您对这个想法的看法
class MyModel:
def __init__(self, session, **data):
"""
Base constructor for almost all model classes, performing common tasks
"""
cls = type(self)
if session:
"""To avoid having an UPDATE right after the INSERT we manually fetch
the next available id using a postgresl internal
SELECT nextval(pg_get_serial_sequence('events', 'id'));
To do that we need the table's name and the sequence
column's name, by chance we use the same name in all our
model
"""
table_name = cls.__tablename__
qry = f"SELECT nextval(pg_get_serial_sequence('{table_name}', 'id'))"
rs = session.execute(qry)
# TODO : find a non ugly way to to that
for row in rs:
next_id = row[0]
# manually set the object id
self.id = next_id
# set the external_id before saving the object in the database
self.ex_id = cls.ex_id_prefix + self.id
session.add(self)
session.flush([self])
【问题讨论】:
-
也许有一种方法可以将
INSERT ... RETURNING与 SQLAlchemy 一起使用。 -
当然有办法,但这不是解决方案,使用 RETURNING 意味着执行我想要避免的更新。
标签: postgresql sqlalchemy flask-sqlalchemy