How it works...

There are two ways to access the database cursor from the recordset: one is from the recordset itself, for example self._cr, and the other is from the environment, for example self.env.cr. This cursor is used to execute database queries. In the preceding example, we saw how you can fetch data through raw queries. The table name is the name of the model after replacing . with _, so the library.book model becomes library_book.

You need to consider a few things before you execute raw queries. Only use raw queries when you have no other choice. By executing raw queries, you are bypassing the ORM layers. You are therefore also bypassing security rules and ORM performance advantages. Sometimes, wrongly-built queries can introduce SQL injection vulnerabilities. Consider the following example, in which queries can allow an attacker to perform SQL injection:

# very bad, SQL injection possible
self.env.cr.execute('SELECT id, name FROM library_book WHERE name ilike + search_keyword + ';')

# good
self.env.cr.execute('SELECT id, name FROM library_book WHERE name ilike %s ';', (search_keyword,))

Don't use the string format function either; it will also allow an attacker to perform SQL injection. Using SQL queries makes your code harder to read and understand for other developers, so avoid using them where possible.

Some Odoo developers believe that executing SQL queries makes operations faster as it bypasses the ORM layer. This is not completely true, however; it depends on the case. In some operations, ORM performs better than RAW queries and faster, because data is served from the recordset cache.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset