【问题标题】:How to get last inserted id in Postgresql with OpenERP如何使用 OpenERP 在 Postgresql 中获取最后插入的 id
【发布时间】:2011-08-16 18:32:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: python postgresql openerp


    【解决方案1】:

    看看RETURNING clause

    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;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        看到 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'})
        

        【讨论】:

          【解决方案4】:

          看起来PostgreSQL RETURNING clause 中的Sentinel's suggestion 是您最容易使用的东西。

          您可能还对 OpenERP 的 ORM 类如何管理新记录的 id 值感兴趣。这是来自orm.create() 方法的sn-p:

              # 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值。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-02-06
            • 2016-10-24
            • 2016-06-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-15
            • 1970-01-01
            相关资源
            最近更新 更多