我有一個插入查詢,並且想要在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