gpt4 book ai didi

python - SQLAlchemy - 如何在提交/更新/查询之前获取对象的 UUID 可用?

转载 作者:行者123 更新时间:2023-12-01 05:14:48 25 4
gpt4 key购买 nike

我是一个新手,试图在将主模型的主 UUID 存储到数据库之前自动实例化它,我不想将对象提交到数据库只是为了获得可用的 UUID。

下面的简短片段来 self 的实际代码。

我认为我需要将初始化附加到某些 SQLAlchemy Hook 中,但我不知道哪个或如何。

我有一个 UUID 助手,如下

class GUID(TypeDecorator):
impl = types.LargeBinary
...

我使用的表格中的

class Row(Model,Base):
__tablename__ = "Row"
id = Column(GUID(), primary_key=True, default=uuid.uuid4)
row_text = Column(Unicode, index=True)
original_row_index = Column(Integer)

当我做这个测试时:

def test_uuid():
row_text = "Just a plain row."
irow = 0

row = Row(row_text, irow)
row.save()
row.commit()

if row.id == None:
print ("row.id == None")
else:
print ("row.id set")

row2 = Row(row_text, irow)
row2.save()
if row2.id == None:
print ("row2.id == None")
else:
print ("row2.id set")

打印

    row.id set
row2.id == None

我使用的Model类如下:

class Model():
def __init__(self):
pass

def save(self):
db = Db.instance()
db.session.add(self)

def commit(self):
db = Db.instance()
db.session.commit()

最佳答案

我认为您不应该使用 commit 方法,而是使用 flush 方法:Difference between flush and commit

刷新不将信息存储到硬盘中,而是创建主键上的所有更改:

Primary key attributes are populated immediately within the flush() process as they are generated and no call to commit() should be required

Link to original

关于python - SQLAlchemy - 如何在提交/更新/查询之前获取对象的 UUID 可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com