3

我有一个插入查询,我想在 OpenERP 中获取最后插入的 id。这是代码:

query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor

如何获取最后插入的 ID?当插入为空时发生了什么?

4

4 回答 4

7

查看RETURNING 子句

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;
于 2011-05-02T06:16:06.640 回答
1

RETURNING如果您运行的是 v8.2+,则效果很好。否则,您可能会考虑使用currval()此处的文档)。

于 2011-05-02T06:20:42.840 回答
1

看到 openerp 标签的链接,我不得不建议你使用 openerp orm。对于调用 create 方法的 orm 将返回新创建记录的 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'})
于 2011-05-27T12:05:39.523 回答
0

看起来SentinelPostgreSQL 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__()方法中看到。

我不知道您要完成什么,但您可能会发现使用该类orm为您创建记录并让它处理细节更容易。例如,create 方法返回新记录的 id 值。

于 2011-05-03T17:22:26.443 回答