Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy-如何获取对象';提交/更新/查询之前是否有可用的UUID?_Python_Sqlalchemy_Instantiation_Uuid - Fatal编程技术网

Python SQLAlchemy-如何获取对象';提交/更新/查询之前是否有可用的UUID?

Python SQLAlchemy-如何获取对象';提交/更新/查询之前是否有可用的UUID?,python,sqlalchemy,instantiation,uuid,Python,Sqlalchemy,Instantiation,Uuid,我是一个试图在将主要模型的主要UUID存储到DB之前自动实例化它的noobie,我不想仅仅为了获得可用的UUID而将对象提交到DB中 下面的简短代码片段来自我的实际代码 我想我需要将初始化附加到一些SQLAlchemy钩子中,但我不知道是哪个或如何附加的 我有一个UUID助手,如下所示 class GUID(TypeDecorator): impl = types.LargeBinary ... 在我使用的表格中 class Row(Model,Base): __tab

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

下面的简短代码片段来自我的实际代码

我想我需要将初始化附加到一些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")
它打印

我使用的模型类如下所示:

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
方法:

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

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

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