Odoo / Model / Query
Query
-
Step 1:
The environment(env) contains an attribute ‘cr’, it’s a cursor for the current database and allows you to execute SQL directly.
Sample Query
self.env.cr.execute(“””SELECT * FROM res_partner”””) self.env.cr.fetchall() Or query = “””SELECT * FROM res_partner””” self.env.cr.execute(query) self.env.cr.fetchall() Different fetch methods are:
1. cr.fetchall(): It will return matching record in the form of a list of tuples 2. cr.fetchone(): same as cr.fetchall() except it return only single record 3. cr.dictfetchall(): It will return a list of dictionary of matching records with key-value pair 4. cr.dictfetchone(): It will return only a single record in the form of a dictionary Create a record
self.env.cr.execute(“INSERT INTO res_partner(name) VALUES(‘ABC’)”) Modify an existing record
self.env.cr.execute("""UPDATE res_partner SET mobile='123' WHERE id=5""") Delete an existing record
self.env.cr.execute("""DELETE FROM res_partner WHERE id=5""")