Executing SQL Queries in Odoo
How to Run SQL Queries within Odoo Modules
Photo by Daniel Schludi on Unsplash
How do I execute an SQL query inside an Odoo module?
Steps:
cr =
self.env.cr
You can use theself.env.cr
object. This object provides a direct connection to the database.cr.execute()
Use thecr.execute()
method to execute the query. You can pass in the query as a string or as a variable containing the query.cr.fetchall()
Use thecr.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.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')
}
ย