【问题标题】:SQLAlchemy returns primary key instead of whole record from insert statementSQLAlchemy 从插入语句返回主键而不是整个记录
【发布时间】:2022-11-15 22:33:12
【问题描述】:

我需要获取在插入语句后在表中创建的整个 orm 实例,因为数据库为主键(数据库 - postgresql)生成了 UUID。

stmt = insert(Table).values(data).returning(Table)
orm_instance = session.execute(stmt).scalar()

其中 Table 定义非常简单:

class Table(BaseModel):
    __tablename__ = "table"

    uuid = Column(UUID(as_uuid=True), primary_key=True)
    name = Column(String)
    # ... another fields

但是,由于未知原因,上面的语句仅返回主键。
目前我必须执行 select 才能继续工作,这很丑陋。

stmt = insert(Table).values(data).returning(Table)
uuid = session.execute(stmt).scalar()

stmt = select(Table).where(Table.uuid == uuid)
orm_instance = session.execute(stmt).scalar()

如何返回整个实例避免提及.returning()中的每一列

【问题讨论】:

    标签: python sqlalchemy orm


    【解决方案1】:

    只需创建您的新对象(没有 PK),将其添加到您的会话中,然后 commit()(或至少 flush())。该对象将获取自动生成的 PK 值:

    new_table = Table(name="x")
    with Session(engine) as sess:
        print(new_table.uuid)  # None
        sess.add(new_table)
        sess.commit()
        print(new_table.uuid)  # 4d97901e-d886-47f5-98a8-4731705afa31
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多