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

2024-09-28 19:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个尝试在主模型的主UUID存储到DB之前自动实例化它的noobie,我不想仅仅为了获得UUID而将对象提交到DB中。在

下面的小片段来自我的实际代码。在

我想我需要将初始化附加到一些SQLAlchemy钩子中,但是我不知道是哪个或者如何。在

我有一个UUID助手,如下所示

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

我用的表中的

^{pr2}$

当我做这个测试时:

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

我使用的模型类如下:

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()

Tags: textselfnoneiddbuuidsavedef
1条回答
网友
1楼 · 发布于 2024-09-28 19:26:37

我想您应该使用的不是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

相关问题 更多 >