【问题标题】:SQLAlchemy - How to get object's UUID available before commit/update/query?SQLAlchemy - 如何在提交/更新/查询之前获取对象的 UUID?
【发布时间】:2014-06-18 20:50:56
【问题描述】:

我是一个菜鸟,试图在将主模型的主 UUID 存储到 DB 之前自动实例化它,我不想将对象提交到 db 只是为了让 UUID 可用。

下面的简短 sn-ps 来自我的实际代码。

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

我有一个如下的 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()

【问题讨论】:

    标签: python sqlalchemy instantiation uuid


    【解决方案1】:

    我想你不应该使用commit 方法,而是flush 方法:Difference between flush and commit

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

    主键属性在生成时立即在 flush() 过程中填充,不需要调用 commit()

    Link to original

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2023-03-29
      • 2017-07-07
      • 2017-09-16
      • 2013-03-16
      • 2022-10-15
      • 1970-01-01
      相关资源
      最近更新 更多