如何在 PonyORM 中获取当前插入的自增主键?

How to get current inserted auto-incremented primary key in PonyORM?

我正在使用以下代码在数据库中创建一个新行,使用 PonyORM:

transportTypes = TransportTypes(
    TransportTypeTitle=data['TransportTypeTitle'], 
    Description=data['Description'],
    LatestUpdateDate=datetime.now()
)

但是,主键仍然设置为None。 table的主键是自增的,如何获取新记录生成的主键?

您需要通过调用 Entity.flush() method:

显式刷新实体

Save the changes made to this object to the database. Usually Pony saves changes automatically and you don’t need to call this method yourself. One of the use cases when it might be needed is when you want to get the primary key value of a newly created object which has autoincremented primary key before commit.

大胆强调我的

对于您的示例,这将是:

transportTypes = TransportTypes(
    TransportTypeTitle=data['TransportTypeTitle'], 
    Description=data['Description'],
    LatestUpdateDate=datetime.now()
)
transportTypes.flush()
print(transportTypes.id)

另一种选择是先显式提交。来自 Saving objects in the database section:

If you need to get the primary key value of a newly created object, you can do commit() manually within the db_session() in order to get this value[.]

# [...]

@db_session
def handler(email):
    c = Customer(email=email)
    # c.id is equal to None
    # because it is not assigned by the database yet
    commit()
    # the new object is persisted in the database
    # c.id has the value now
    print(c.id)

因此,当使用 db_session 作为上下文管理器时,它会在上下文退出时自动提交,您可以使用:

with db_session:
    transportTypes = TransportTypes(
        TransportTypeTitle=data['TransportTypeTitle'], 
        Description=data['Description'],
        LatestUpdateDate=datetime.now()
    )

# context has been exited, the session has been committed
# and the identity map has been cleared, so accessing attributes loads
# them fresh from the database
print(transportTypes.id)