如何在OpenERP中使用Postgresql获取最后插入的id?

3

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

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

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

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;

1

1

RETURNING 在运行 v8.2+ 的情况下非常好用。否则,您可能需要使用 currval()在此处查看文档)。


0

看起来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值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接