Executing SQL Queries in Odoo

How to Run SQL Queries within Odoo Modules

How do I execute an SQL query inside an Odoo module?

Steps:

  1. cr = self.env.cr
    You can use the self.env.cr object. This object provides a direct connection to the database.

  2. cr.execute()
    Use the cr.execute() method to execute the query. You can pass in the query as a string or as a variable containing the query.

  3. cr.fetchall()
    Use the cr.fetchall() method to fetch the results of the query. This will return a list of tuples, where each tuple represents a row in the result set.

  4. Do something with the results

Example:

cr = self.env.cr
Execute the query
cr.execute(""" SELECT id ,name,email
FROM res_partner
WHERE id in %s
""", (((1, 2)),))
res = cr.fetchall()
Do something with the results
res_data = { id: (name, email) for id, name, email in res }
Result
{
1: ('My Company (San Francisco)', info@yourcompany'),
2: ('OdooBot', 'odoobot@example')
}

Result:

{
1: ('My Company (San Francisco)', info@yourcompany'),
2: ('OdooBot', 'odoobot@example')
}
ย