sqlalchemy flush() 并插入 id? [英] sqlalchemy flush() and get inserted id?

查看:19
本文介绍了sqlalchemy flush() 并插入 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

f = Foo(bar='x')
session.add(f)
session.flush()

# do additional queries using f.id before commit()
print f.id # should be not None

session.commit()

但是当我尝试时 f.idNone .我怎样才能让它工作?

But f.id is None when I try it. How can I get this to work?

推荐答案

您的示例代码应该可以正常工作.SQLAlchemy 应该为 f.id 提供一个值,假设它是一个自动生成的主键列.主键属性在生成时立即在 flush() 过程中填充,并且不需要调用 commit().所以这里的答案在于以下一项或多项:

Your sample code should have worked as it is. SQLAlchemy should be providing a value for f.id, assuming its an autogenerating primary-key column. Primary-key attributes are populated immediately within the flush() process as they are generated, and no call to commit() should be required. So the answer here lies in one or more of the following:

  1. 映射的详细信息
  2. 如果使用的后端有任何奇怪的怪癖(例如,SQLite 不会为复合主键生成整数值)
  3. 当您打开 echo 时发出的 SQL 会说什么

这篇关于sqlalchemy flush() 并插入 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆