How to Execute Query in Odoo 15

July 6, 2022

Odoo ORM saves our time and speeds up the development process and doesn’t need any SQL knowledge to use an ORM. But it has a tendency to be slow and cannot compete with complex queries. So in this blog, we discuss how to use SQL queries in Odoo.

For example, In one case, we have to create a report from a large amount of data. Their performance is a key consideration. If we are using the ORM, using this technique would require a long time to retrieve data because ORM is slower than Row SQL Queries. Because of this, a query needs to be run.

To execute SQL queries, we need a cursor ‘cr’ attribute which is used to point the current database in the environment (env). This sends this query to PostgreSQL and executes it.

How to Execute Query: Examples

For example, for query, creating a record in the table res_partner

query = """ INSERT INTO res_partner (name, email) VALUES ('Demo partner', '') """

Let’s look for another example fetching all the data from a model

query = """Select * from res_users"""zz

After executing this query, we get all the data from the model res_users

Fetching Methods

Let’s have a look at the different fetching methods:

  1. cr.fetchall () – will give you all the matching records in the form of the list of tuple [(”), (”), …].
  2. cr.fetchone () – works the same as cr. dictfetchall () except it returns only a single record {”: ”}.
  3. cr.dictfetchall () – will give you all the matching records in the form of the list of dictionary containing key, value [{”: ”}, {”: ”}, …].
  4.  cr.dictfetchone () – works the same as cr.dictfetchall () except it returns only a single record {”: ”}.

Output of the Query

In your given query, the output would be:

  • The end result of cr.dictfetchall () is [[‘reg_no’: 123], [‘reg_no’: 543]].
  • If you run cr.dictfetchone () the result is {‘reg_no’: 123}.
  • When you run cr.fetchall (), the result is ‘ [ (123), (543)]’.
  • CR.fetchone () returns ‘ (123)’.

CRUD Operations

Let’s have a look at the CRUD (Create operations, Read operations, Update operations, Delete operations)

  • Create –“INSERT INTO res_company (name) VALUES (‘demo company)”)
  • Read –“””SELECT * FROM res_company”””)
  • Update –“””UPDATE res_company SET phone=’23’ WHERE id=50″””)
  • Delete –“””DELETE FROM res_company WHERE id=5″””)

Request Your Free Quote

"Unlock the Full Potential of Your Business with Odoo ERP!"

"Get a Cost Estimate for Your ERP Project, Absolutely FREE!"

Get a Free Quote

Leave a Reply

Your email address will not be published. Required fields are marked *