我有一个插入查询,想在OpenERP中获取最后插入的id。以下是代码:
query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor
如何获取最后插入的 ID?当插入为空时会发生什么?
我有一个插入查询,想在OpenERP中获取最后插入的id。以下是代码:
query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor
如何获取最后插入的 ID?当插入为空时会发生什么?
看一下RETURNING子句。
INSERT INTO table [ ( column [, ...] ) ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
[ RETURNING * | output_expression [ AS output_name ] [, ...] ]
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;
看到openerp标签的链接,我建议您使用openerp orm。对于orm调用create方法将返回新创建记录的id。(它还适用于您可能定义的任何osv_memory类)
参考:http://doc.openerp.com/v6.0/developer/2_5_Objects_Fields_Methods/methods.html#osv.osv.osv.create
示例:
new_id = self.pool.get('model.name').create(cr, uid, {'name': 'New Name'})
看起来Sentinel的建议和PostgreSQL RETURNING子句是你最容易使用的东西。
你可能也对OpenERP的ORM类如何管理新记录的id值感兴趣。这里有一个orm.create()
方法的片段:
# Try-except added to filter the creation of those records whose filds are readonly.
# Example : any dashboard which has all the fields readonly.(due to Views(database views))
try:
cr.execute("SELECT nextval('"+self._sequence+"')")
except:
raise except_orm(_('UserError'),
_('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
id_new = cr.fetchone()[0]
它使用每个表的序列来生成新的id值。序列的名称默认为表名加上'_id_seq',就像您在orm.__init__()
方法中看到的那样。
我不知道您想要实现什么,但您可能会发现使用{{link2:orm
类}}为您创建记录并让它处理细节更容易。例如,create方法返回新记录的id值。