How to get the last inserted id in Postgresql using OpenERP

I have an insert request and want to get the last inserted id in OpenERP. Here is the code:

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

How to get the last inserted identifiers? What happened when the insert is empty?

+3
source share
4 answers

Take a look at the RETURNING clause .

INSERT INTO table [ ( column [, ...] ) ]
    { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
    [ RETURNING * | output_expression [ AS output_name ] [, ...] ]

Insert one row into the table allocators, returning the sequence number generated by the DEFAULT clause:

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
   RETURNING did;
+7
source

RETURNINGworks great if you use v8.2 +. Otherwise, you'll probably be looking currval()( doc here ).

+1
source

openerp, openerp orm. orm create . ( 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'})
+1

, 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__() method.

, , orm . , create id .

0

All Articles