我有一个插入查询,并且想要在OpenERP中获取最后插入的ID。这里是代码:如何使用OpenERP在Postgresql中获取最后插入的ID
query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor
如何获取最后插入的ID(s)?插入空白时发生了什么?
我有一个插入查询,并且想要在OpenERP中获取最后插入的ID。这里是代码:如何使用OpenERP在Postgresql中获取最后插入的ID
query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor
如何获取最后插入的ID(s)?插入空白时发生了什么?
INSERT INTO table [ (column [, ...]) ]
{ DEFAULT VALUES | VALUES ({ expression | DEFAULT } [, ...]) [, ...] | query }
[ RETURNING * | output_expression [ AS output_name ] [, ...] ]
插入一行到表distributors,返回由DEFAULT子句中生成的序列号:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;
RETURNING
如果你正在运行V8.2 +的伟大工程。否则,你可能会使用currval()
(doc here)。
看起来像Sentinel's suggestion的PostgreSQL RETURNING clause是最容易使用的东西。
您可能还对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__()
method中看到。
我不知道你在努力完成什么,但是你可能会发现使用the orm
class为你创建记录并让它处理细节更容易。例如,the create method返回新记录的id值。
看到链接到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'})
谢谢。你节省了我的一天。 – Zeck 2011-05-02 06:29:14