4. Modularity
• Modular programming is a software design
technique to split your code into separate
parts. These parts are called modules. The
focus for this separation should be to have
modules with no or just few dependencies
upon other modules.
• The executable application will be created by
putting the modules together.
6. Do not reinvent the wheel !!
• Before beginning a new module
development, find out if there is any
module that might solve your problem
totally or partially.
• If you decide to develop a new module,
analyze what features you will need in
other modules, and try to encapsulate them
in other module so that you can inherit
them later
7. Module structure in odoo
Directories:
• A module is organized in important
directories that contain the business logic.
• Module directories are specified by using the
–-addons-path.py option.
• An Odoo module is declared by its manifest.
• The manifest file serves to declare a python
package as an Odoo module and to specify
module metadata.
8. • A module is also a Python package with a
__init__.py file, containing import
instructions for various Python files in
the module.
9. Directories
• data/ : demo and data xml
• models/ : models definition
• controllers/ : contains controllers (HTTP
routes).
• views/ : contains the views and templates
• static/ : contains the web assets, separated
into css/, js/, img/, lib/, ...
10. Other optional directories compose the
module:
wizard/ : regroups the transient models
(formerly osv_memory) and their views.
report/ : contains the reports (RML report
[deprecated], models based on SQL views (for
reporting) and other complex reports). Python
objects and XML views are included in this
directory.
tests/ : contains the Python/YML tests
Security/
i18n/: used for translating
11. Odoo follows an MVC-like architecture:
• The model layer, defining the structure of the
app's data.
• The view layer, describing the user interface
• The controller layer, supporting the business
logic of the application
12. Odoo provides a mechanism to help set up a new
module, odoo-bin has a subcommand scaffold
to create an empty module:
odoo-bin scaffold <module name> <where to
put it>
Starting with odoo
13. Configuring the addons path:
• The Odoo server has a configuration option called
addons_path to set where the server should look
for modules. By default, this points to the /addons
directory, where the Odoo server is running.
• We can provide not only one, but a list of
directories where modules can be found. This allows
us to keep our custom modules in a different
directory, without having them mixed with the
official addons.
$ ./odoo-bin -d demo –addons path="../custom_addons_app,./addons"
14. Manifest content
• name (str, required)the human-readable name
of the module .
• version (str)this module's version, should
follow semantic versioning rules .
• description (str)extended description for the
module.
• author (str)name of the module author.
• website (str)website URL for the module
author.
• license (str, defaults: LGPL-3)distribution
license for the module
15. category (str, default: Uncategorized)
classification category within Odoo, rough
business domain for the module.
Although using existing categories is
recommended, the field is freeform and
unknown categories are created on-the-fly.
data (list(str))List of data files which must
always be installed or updated with the
module. A list of paths from the module root
directory.
16. demo (list(str))List of data files which are only
installed or updated in demonstration mode.
installable (bool default: False)Whether a user
should be able to install the module from the
Web UI or not.
auto_install (bool, default: False)If True, this
module will automatically be installed if all of its
dependencies are installed.
external_dependencies (dict(key=list(str)))A
dictionary containing python and/or binary
dependencies.
17. depends (list(str))Odoo modules which must
be loaded before this one, either because this
module uses features they create or because
it alters resources they define . When a
module is installed, all of its dependencies are
installed before it. Likewise dependencies are
loaded before a module is loaded.
application (bool, default: False)Whether the
module should be considered as a fully-
fledged application (True) or is just a
technical module (False) that provides some
extra functionality to an existing application
module.
18. css (list(str))Specify css files with custom
rules to be imported, these files should be
located in static/src/css inside the module.
images (list(str))Specify image files to be used
by the module.
maintainer (str)Person or entity in charge of
the maintenance of this module, by default it is
assumed that the author is the maintainer.
19. {pre_init, post_init, uninstall}_hook (str)Hooks
for module installation/uninstallation, their value
should be a string representing the name of a
function defined inside the module's __init__.py.
pre_init_hook takes a cursor as its only
argument, this function is executed prior to the
module's installation.
20. post_init_hook takes a cursor and a registry as
its arguments, this function is executed right
after the module's installation.
uninstall_hook takes a cursor and a registry as
its arguments, this function is executed after
the module's uninstallation.
These hooks should only be used when
setup/cleanup required for this module is either
extremely difficult or impossible through the
api.
21. File naming
• For views declarations, split backend views
from (frontend) templates in 2 different
files.
• For models, split the business logic by sets of
models, in each set select a main model, this
model gives its name to the set. If there is
only one model, its name is the same as the
module name.
22. For each set named <main_model> the following
files may be created:
• models/<main_model>.py
• models/<inherited_main_model>.py
• views/<main_model>_templates.xml
• views/<main_model>_views.xml
23. • For data, split them by purpose : demo or
data. The filename will be the main_model
name, suffixed by _demo.xml or _data.xml.
• For controllers, the only file should be named
main.py. Otherwise, if you need to inherit an
existing controller from another module, its
name will be <module_name>.py. Unlike models,
each controller class should be contained in a
separated file.
24. • For static files, since the resources can be
used in different contexts (frontend,
backend, both), they will be included in only
one bundle. So, CSS/Less, JavaScript and
XML files should be suffixed with the name
of the bundle type.
• Don't link data (image, libraries) outside
Odoo: do not use an URL to an image but copy
it in our codebase instead.
29. Data files
• Odoo is a highly data driven system. Although
behavior is customized using Python code ,
part of a module's value is in the data it sets
up when loaded.
• Module data is declared via data files .
• Data files have to be declared in the manifest
file to be loaded, they can be declared in the
'data' list (always loaded) or in the 'demo'
list (only loaded in demonstration mode).
• XML files with <record> elements creates or
updates a database record.
30. XML files
To declare a record in XML, use the record
notation
• Place id attribute before model.
• For field declaration, name attribute is first.
Then place the value either in the field tag,
either in the eval attribute, and finally other
attributes (widget, options, ...) ordered by
importance.
• The tag <data> is only used to set not-updatable
data with noupdate=1. If there is only not-
updatable data in the file, the noupdate=1 can be
set on the <odoo> tag and do not set a <data> tag.
32. Odoo supports custom tags acting as
syntactic sugar:
• menuitem: use it as a shortcut to declare a
ir.ui.menu.
• template: use it to declare a QWeb View
requiring only the arch section of the view.
• report: use to declare a report action.
• act_window: use it if the record notation
can't do what you want.
33. Naming xml_id
• For a menu: <model_name>_menu
• For a view: <model_name>_view_<view_type>,
where view_type is kanban, form, tree,
search, ...
• For an action: the main action respects
<model_name>_action. Others are suffixed
with _<detail>, where detail is a lowercase
string briefly explaining the action. This is
used only if multiple actions are declared for
the model.
34. • For a group:
<model_name>_group_<group_name> where
group_name is the name of the group,
generally 'user', 'manager', ...
• For a rule:
<model_name>_rule_<concerned_group> where
concerned_group is the short name of the
concerned group ('user' for the
'model_name_group_user', 'public' for public
user, 'company' for multi-company rules, ...).
38. Inherited view:
• The naming pattern of inherited view is
<base_view>_inherit_<current_module_name>. A
module may only extend a view once. Suffix the
original name with
_inherit_<current_module_name> where
current_module_name is the technical name of
the module extending the view.
<record
id="inherited_model_view_form_inherit_my_module"
model="ir.ui.view">
...
</record>
39. XML views
• Basic views:
Views define the way the records of a model
are displayed. Each type of view represents a
mode of visualization (a list of records, a graph
of their aggregation, …). Views can either be
requested generically via their type (e.g. a list
of partners) or specifically via their id. For
generic requests, the view with the correct
type and the lowest priority will be used (so the
lowest-priority view of each type is the default
view for that type).
40. Generic view declaration:
• A view is declared as a record of the model
ir.ui.view.
• The view type is implied by the root element
of the arch field
• The view's content is XML thus the arch field
must be declared as type="xml" to be parsed
correctly.
41. Tree views:
• Tree views, also called list views, display
records in a tabular form.
• Their root element is <tree>. The simplest
form of the tree view simply lists all the
fields to display in the table (each field as a
column):
<tree string="Idea list">
<field name="name"/>
<field name="inventor_id"/>
</tree>
42. Tree views can take supplementary attributes
to further customize their behavior:
• decoration-{$name} allow changing the style
of a row's text based on the corresponding
record's attributes.
• Values are Python expressions. For each
record, the expression is evaluated with the
record's attributes as context values and if
true, the corresponding style is applied to the
row. Other context values are uid (the id of
the current user) and current_date (the
current date as a string of the form yyyy-
MM-dd).
43. • {$name} can be bf (font-weight: bold), it
(font-style: italic), or any bootstrap
contextual color (danger, info, muted,
primary, success or warning).
• Editable :Either "top" or "bottom". Makes the
tree view editable in-place (rather than
having to go through the form view), the value
is the position where new rows appear.
• Invisible.
44. • <tree string="Idea Categories"
decoration-info="state=='draft'"
decoration-danger="state=='trashed'">
• <field name="name"/>
• <field name="state“
invisible="'product_id' not in context"/>/>
• </tree>
45. Form views:
• Forms are used to create and edit single
records.
• Their root element is <form>. They are
composed of high-level structure elements
(groups, notebooks) and interactive elements
(buttons and fields):
47. Domains
• In Odoo, Domains are values that encode
conditions on records. A domain is a list of
criteria used to select a subset of a model's
records. Each criteria is a triple with a field
name, an operator and a value.
• By default criteria are combined with an
implicit AND. The logical operators &(AND),
|(OR)and!(NOT) can be used to explicitly
combine criteria. They are used in prefix
position (the operator is inserted before its
arguments rather than between)
48. Search views:
• Search views customize the search field
associated with the list view (and other
aggregated views). Their root element is
<search> and they're composed of fields
defining which fields can be searched on:
<search>
<field name="name"/>
<field name="inventor_id"/>
</search>
49. • Search view <field> elements can have a
@filter_domain that overrides the domain
generated for searching on the given field. In
the given domain.
• Search views can also contain <filter> elements,
which act as toggles for predefined searches.
• Filters must have one of the following
attributes:
• Domain add the given domain to the current
search.
• Context add some context to the current
search; use the key group_by to group results on
the given field name.
51. Graph views
• Graph views allow aggregated overview and
analysis of models, their root element is
<graph>.
• Graph views have 4 display modes, the default
mode is selected using the mandatory @type
attribute taking the values:
row (default)the field should be aggregated by
default.
Measure the field should be aggregated rather
than grouped on.
52. The display modes:
• Bar (default)a bar chart, the first dimension
is used to define groups on the horizontal
axis, other dimensions define aggregated bars
within each group.
• By default bars are side-by-side, they can be
stacked by using @stacked="True" on the
<graph>
• Line 2-dimensional line chart.
• Pie 2-dimensional pie
<graph string="Total idea score by Inventor">
<field name="inventor_id"/>
<field name="score" type="measure"/>
</graph>
53. Calendars:
• Displays records as calendar events. Their root
element is <calendar> and their most common
attributes are:
• colorThe name of the field used for color
segmentation. Colors are automatically
distributed to events, but events in the same
color segment (records which have the same
value for their @color field) will be given the
same color.
• date_start record's field holding the start
date/time for the event.
• date_stop (optional)record's field holding the
end date/time for the event
56. • Kanban:
• Used to organize tasks, production processes,
etc… their root element is <kanban>.
• A kanban view shows a set of cards possibly
grouped in columns. Each card represents a
record, and each column the values of an
aggregation field.
• Kanban views define the structure of each
card as a mix of form elements (including
basic HTML) and Qweb.
60. View inheritance
• Instead of modifying existing views in place
(by overwriting them), Odoo provides view
inheritance where children "extension" views
are applied on top of root views, and can add
or remove content from their parent.
• An extension view references its parent using
the inherit_id field, and instead of a single
view its arch field is composed of any number
of xpath elements selecting and altering the
content of their parent view.
61. • Expr:An XPath expression selecting a single
element in the parent view. Raises an error if
it matches no element or more than one
position Operation to apply to the matched
element.
• Inside:appends xpath's body at the end of
the matched element.
• Replace: replaces the matched element with
the xpath's body, replacing any $0 node
occurrence in the new body with the original
element
62. • Before:inserts the xpath's body as a sibling
before the matched element.
• After: inserts the xpaths's body as a sibling
after the matched element.
• Attributes : alters the attributes of the
matched element using special attribute
elements in the xpath's body.
63. <!-- improved idea categories list -->
• <record id="idea_category_list2"
model="ir.ui.view">
• <field name="name">id.category.list2</field>
<field name="model">idea.category</field>
<field name="inherit_id"
ref="id_category_list"/>
• <field name="arch" type="xml">
<!-- find field description and add the field idea_ids
after it -->
• <xpath expr="//field[@name='description']"
position="after">
• <field name="idea_ids" string="Number of
ideas"/>
• </xpath>
• </field>
• </record>
67. What is Cross Site Request
Forgery (CSRF)?
Cross-site request forgery (CSRF)
vulnerabilities can be used to trick a user’s
browser into performing an unwanted action
on your site.
69. Damaged Causes By CSRF:
In Net-banking attacker can forge the request
and send it to victim to steal money from
Victim’s account .
Personal health information can be stolen or
modified in a hospital database .
Attacker force victim to perform unwanted
action which affect their profile .
72. CSRF In Odoo:
You must add this line of code in your
form :
`csrf_token` e.g. :
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
73.
74. What Is Odoo Security?
It’s ability to control what user can
do and what user can't-do on a
different level .
Have four basic operations: read,
write, create, and unlink(Delete) .
75. Why would I want to have field
level access control in Odoo?
Restrict temporary or part-time workers from
data they do not need to see.
It makes the system easier to use and the forms
less cluttered.
It's important to learn all aspects of Odoo's access
rights before configuring Odoo for production.
77. Groups:
How to assign users to groups?
Security access in Odoo is
configured through security
groups: permissions are given to
groups and then groups are
assigned to users.
78. Why should I use groups to
restrict access rather than
removing the fields?
No. This is a bad idea because Odoo may
have processes and other depencencies that
are expecting that field to be available on
the form.
80. Here you can see, you can add as
many as users under Users tab so that
only that users can view
Accounting&Finance/Billing.
81. Access Control List:
In Odoo, views and menus are restricted to a user due to
access right permission. Only admin has right to view all
records. Access right permission is managed by creating an
ir.model.access.csv file.
This file can Grant Available permissions are :
creation (perm_create).
searching and reading (perm_read).
updating existing records (perm_write).
deleting existing records (perm_unlink).
Define group to a model(optional) :
– If no group: access rights applies to all users
– If group: access rights applies to member of that group
82. Access controls are additive, for example if the user
belongs to one group which allows writing and another
which allows deleting, they can both write and delete.
Here is the steps define ir.model.access.csv file for custom
model:
Step 1 : Create Security folder in your custom module.
Blog/security
Step 2 : Make ir.model.access.csv file in Security folder.
Blog/security/ir.model.access.csv
Step3 : Edit in __manifest__.py
'data': [
'security/ir.model.access.csv',
],
83. Step4 : Write following code in your
ir.model.access.csv
Defining Access Rights ( ir.model.access.csv )
id = unique identity for the permission (Example:access_blog_post_user)
name = unique name for the permission (Example:blog.post.user)
model_id/id = the model unique name of the class you want apply
permission on (Example: model_blog_post)
group_id/id = Permission apply on group(Example:
Blog.group_blog_user)
Where Blog:module name , group_blog_user :group id
perm_read,perm_write,perm_create,perm_unlink = the 4 values for the
relative permission to read, write,create,unlink record on defined class. 1 is
True and 0 is False
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_blog_post_user,blog.post.user,model_blog_post,Blog.group_blog_user,1,0,0,0
84.
85. Record Rules:
Record Rules are certain conditions that the records must
satisfy for the operations such as : (read,write,delet,create)
to be allowed.
it is applied , record-by-record after the access control has
been applied.
Record Rules can be defined from the menu also without
creating any file.
A set of permissions to which it applies (e.g. if perm_read is
set, the rule will only be checked when reading a record)
A set of user groups (no group means global rule)
A domain for filtering data
If filter matches: It is accessible
If filter does not matches: It is not accessible
88. Field Access
An ORM field can have a groups attribute
providing a list of groups.If the current user is
not in one of the listed groups, he will not have
access to the field:
e.g:
90. Dose Odoo Store Passwords in
Clear text??!!
Yes by default it does, you can change this behavior if
you install the module auth_crypt .
But as we all know that in term of security it is a very
bad practice to store passwords without strong hashing
(SHA-256+) and salting!
What Odoo say about this?
Well, actually that's a feature, so that it's possible to
recover lost passwords.
As for the reason for cleartext passwords: once you
switch to encrypted passwords you can't recover user
passwords anymore . So enabling it is a choice, because
there's no going back. We don't currently plan to make
passwords encrypted by default.
92. Contents
• What we mean by ORM in odoo?
• Structural attributes.
• Fields.
• Method decorators.
• Common ORM methods.
• Domains.
• Inheritance.
93. What we mean by ORM in odoo?
• In Odoo, the data model is described and
manipulated through Python classes and objects.
It is the ORM job to bridge the gap - as
transparently as possible for the developer -
between Python and the underlying relational
database (PostgreSQL), which will provide the
persistence we need for our objects. And as we
know “Every thing in Odoo is an object”.
94. • A key component of Odoo is the ORM layer. This layer avoids having
to write most SQL by hand and provides extensibility and security
services.
• Business objects are declared as Python classes
extending model which integrates them into the automated
persistence system.
• Models can be configured by setting a number of attributes at their
definition. The most important attribute is _name which is required
and defines the name for the model in the Odoo system. Here is a
minimally complete definition of a model:
95. The system will later instantiate the class once per database (on
which the class' module is installed).
96. Structural attributes
• _name :
business object name, in dot-notation (in module namespace) .
• _rec_name:
Alternative field to use as name, used by osv’s name_get() (default: 'name').
• _inherit:
If _name is set, names of parent models to inherit from. Can be a str if
inheriting from a single parent
If _name is unset, name of a single model to extend in-place
97. Structural attributes
• _inherits :
dictionary mapping the _name of the parent
business objects to the names of the
corresponding foreign key fields to use:
99. Structural attributes
• _auto:
Whether a database table should be created (default:
True)
• _table:
Name of the table backing the model created when
_auto, automatically generated by default.
100. Structural attributes
• _constraints
• list of (constraint_function, message, fields)
defining Python constraints. The fields list is
indicative
Deprecated since version 8.0: use constrains().
102. Fileds
• Fields are used to define what the model can store
and where. Fields are defined as attributes on the
model class:
103. • Simple fields :
fields.Char
fields.Integer
fields.Float
fields.Date
fields.Selection :
When extending a model, if you want to add possible values to a selection
field, you may use the selection_add keyword :
fields.Text
fields.Boolean
fields.Monetary
fields.Html: Used to store HTML, provides an HTML widget.
104. • Reserved fields:
Odoo creates a few fields in all models. These fields are managed by the
system and shouldn't be written to. They can be read if useful or
necessary:
id (Id)The unique identifier for a record in its model.
create_date (Datetime)Creation date of the record.
create_uid (Many2one)User who created the record.
write_date (Datetime)Last modification date of the record.
write_uid (Many2one)user who last modified the record.
This information is available from the web client, navigating to the
Developer Mode menu and selecting the View Metadata option.
105. • Computed Fields :
Fields can be computed (instead of read straight from the database)
using the compute parameter. It must assign the computed value to the
field. If it uses the values of other fields, it should specify those fields
using depends() :
106. computed fields are not stored by default, they are computed and
returned when requested. Setting store=True will store them in the
database and automatically enable searching.
The decorator odoo.api.depends() must be applied on the compute
method to specify the field dependencies
107. to allow setting values on a computed field, use the inverse parameter. It is
the name of a function reversing the computation and setting the
relevant fields.
multiple fields can be computed at the same time by the same method,
just use the same method on all fields and set all of them :
108. • The computed field can be read, but it can't
be searched or written. To enable these
operations, we first need to implement
specialized functions for them. Along with the
compute function, we can also set a search
function, implementing the search logic, and
the inverse function, implementing the write
logic.
109. • Related fields :
A special case of computed fields are related (proxy) fields, which provide
the value of a sub-field on the current record. They are defined by
setting the related parameter and like regular computed fields they
can be stored.
• Behind the scenes, related fields are just computed fields that
conveniently implement search and inverse methods. This means that
we can search and write on them out of the box, without having to
write any additional code.
110. • onchange: updating UI on the fly :
• When a user changes a field's value in a form
(but hasn't saved the form yet), it can be
useful to automatically update other fields
based on that value e.g. updating a final total
when the tax is changed or a new invoice line
is added.
111. • computed fields are automatically checked
and recomputed, they do not need an
onchange
• for non-computed fields, the onchange()
decorator is used to provide new field values
112. • Common attributes :
There are many attributes may be provided when instantiating a
field as a common attributes :
String :
the label of the field seen by users (string); if not set, the ORM takes
the field name in the class (capitalized).
Help:
the tooltip of the field seen by users (string)
Readonly:
whether the field is readonly (boolean, by default False)
Required:
whether the value of the field is required (boolean, by default False)
Index:
whether the field is indexed in database (boolean, by default False)
Common fields attributes
113. default :
the default value for the field; this is either a static value, or a
function taking a recordset and returning a value; use
default=None to discard default values for the field.
states :
a dictionary mapping state values to lists of UI attribute-value
pairs; possible attributes are: 'readonly', 'required',
'invisible'. Note: Any state-based condition requires the
state field value to be available on the client-side UI. This is
typically done by including it in the relevant views, possibly
made invisible if not relevant for the end-user.
114. groups :
comma-separated list of group xml ids (string); this restricts the field access
to the users of the given groups only
copy (bool) :
whether the field value should be copied when the record is duplicated
(default: True for normal fields, False for one2many and computed fields,
including property fields and related fields)
oldname (string):
the previous name of this field, so that ORM can rename it automatically at
migration
Translate(bool) :
In case of True it means can be translated
size (int):
the maximum size of values stored for that field
115. • Relational fields :
1. Many2one :
The many2one relationship accepts two positional arguments: the related
model (corresponding to the comodel keyword argument) and the title
string. It creates a field in the database table with a foreign key to the
related table.
Parameters :
• comodel_name : name of the target model (string) ‘mandotary’
• domain : an optional domain to set on candidate values on the client
side (domain or string)
• context : an optional context to use on the client side when handling
that field (dictionary)
• ondelete : what to do when the referred record is deleted; possible
values are: 'set null', 'restrict', 'cascade'
• auto_join : whether JOINs are generated upon search through that field
(boolean, by default False)
• delegate : set it to True to make fields of the target model accessible
from the current model (corresponds to _inherits)
116. 2. One2many :
An inverse of many2one can be added to the other end of the relationship. This has
no impact on the actual database structure, but allows us easily browse from the
one side of the many related records. A typical use case is the relationship
between a document header and its lines.
One2many makes it easy for a parent to keep track of its children.
• Parameters :
comodel_name : name of the target model (string)
inverse_name : name of the inverse Many2one field in comodel_name (string)
domain : an optional domain to set on candidate values on the client side (domain
or string)
context : an optional context to use on the client side when handling that field
(dictionary)
auto_join : whether JOINs are generated upon search through that field (boolean,
by default False)
limit : optional limit to use upon read (integer)
(Comodel_name + inverse_name ) are mandatory fields.
117. 3.Many2many :
At the database level, it does not add any columns to the existing tables. Instead, it
automatically creates a new relationship table that has only two ID fields with the foreign
keys for the related tables. The relationship table name and the field names are
automatically generated. The relationship table name is the two table names joined with an
underscore with _rel appended to it.
Parameters
• comodel_name : name of the target model (string) ‘mandatory’
• Parameters
• relation : optional name of the table that stores the relation in the database (string)
• column1 : optional name of the column referring to "these" records in the table relation
(string)
• column2 : optional name of the column referring to "those" records in the table relation
(string)
• domain : an optional domain to set on candidate values on the client side (domain or string)
• context : an optional context to use on the client side when handling that field (dictionary)
• limit : optional limit to use upon read (integer)
118. Method decorators
• Before we go to decorators we need first to know little things about
recordest
• Recordset :
New in version 8.0 , Interaction with models and records is performed
through recordsets, a sorted set of records of the same model.
Methods defined on a model are executed on a recordset, and their self is
a recordset
119. • Record cache and prefetching :
Odoo maintains a cache for the fields of the records, so that not every
field access issues a database request, which would be terrible for
performance. The following example queries the database only for the
first statement:
To avoid reading one field on one record at a time, Odoo prefetches
records and fields following some heuristics to get good performance.
Once a field must be read on a given record, the ORM actually reads
that field on a larger recordset, and stores the returned values in cache
for later use. The prefetched recordset is usually the recordset from
which the record comes by iteration. Moreover, all simple stored fields
(boolean, integer, float, char, text, date, datetime, selection,
many2one) are fetched altogether; they correspond to the columns of
the model's table, and are fetched efficiently in the same query.
120. Method decorators
• decorators are important for the server to know how to handle the
method.
• There are two different API styles, namely the "traditional" and "record"
styles.
• In the "traditional" style, parameters like the database cursor, user id,
context dictionary and record ids (usually denoted as cr, uid, context, ids)
are passed explicitly to all methods. In the "record" style, those
parameters are hidden into model instances, which gives it a more object-
oriented feel.
• A decorator is a function that takes a function as input and returns a
function.
• The anatomy of the decorator is: @decorator-expression
• Decorator-expression is an expression that returns a callable thing. The
callable thing has to take a single argument. Function definition is a
function definition (it, therefore, must begin with def).
• In older version of odoo, we use a cursor, uid, context and ids for defining
all method.
• In odoo 9, odoo 10 we use self as the parameter when defining a method
with certain method decorators.This decorator are passed the parameters
explicitly to the method. Which provide a smooth way to write functions
and avoid complications.
121. • 1.@api.one:
It is specific for one record and cannot be used for multiple
records. Self is redefined as current record.
Example
@api.one
def get_product(self):
self.product_name = ‘desktop’
This function will automatically write product name field of each
record with ‘desktop’.
122. • 2.@api.multi:
It can use for multiple records, so we can
loop through it. Here Self-contains
recordset so that we need for loop for
iterating through each record.
Example
@api.multi
def get_product(self):
For the record in self:
self.product_name = ‘desktop’
123. • 3.@api.model:
This decorator will convert old API calls to decorated function to new
API signature.
• 4.@api.depends:
This decorator is specifically used for computing fields in odoo. The
decorator function works only if any of the fields specified in the
@api.depends is changed in the form.
Dependencies can be dotted paths when using sub-fields.
Example:
@api.depends(‘partner_id.street’)
def _get_street(self):
for record in self:
for line in record.partner_id:
record.street = line.street
Computed field are not stored by default, they have computed the
function and return the value.We use store = True to store the
computed value to the database.
124. • 5.@api.onchange:
This decorator will avoid the on change attribute in the xml file.
The fields are written as the parameter of the function.
Example:
@api.onchange(‘date_of_birth’,’age’)
def onchange_age_calculation(self ):
if not self.date_of_birth:
self.age = 0
else:
today_date = datetime.now().year
date_split = self.date_of_birth.split(‘-‘,1)
birth_year = date_split[0]
self.age = today_date -int(birth_year)
This function will automatically write age field when changing
the value of date_of_birth field in form view.
125. • 6.@api.constrains:
This decorator will ensure that decorated
function will be called on creating, write,
unlink operation. It will act as a constraint
checker. This will especially use for warning
messages and validation.
126. Common ORM methods
• search() : Takes a search domain, returns a
recordset of matching records:
• create() : Takes a number of field values,
and returns a recordset containing the
record created
127. • write()Takes a number of field values,
writes them to all the records in its
recordset. Does not return anything:
• browse()Takes a database id or a list of ids
and returns a recordset:
128. • ensure_one() checks that the recordset is a
singleton (only a single record), raises an
error otherwise:
129. Domains
• A domain is a list of criteria, each criterion
being a triple (either a list or a tuple) of
(field_name, operator, value) where:
• field_name (str) :
a field name of the current model, or a
relationship traversal through a Many2one
using dot-notation e.g. 'street' or
'partner_id.country'operator (str)an
operator used to compare the field_name
with the value.
130. • operator (str) :
an operator used to compare the field_name with the value. Valid operators are:
1. =equals to
2. !=not equals to
3. > greater than
4. >= greater than or equal to
5. <less than
6. <=less than or equal to
7. =?unset or equals to (returns true if value is either None or False, otherwise behaves like
=)
8. =like : matches field_name against the value pattern. An underscore _ in the pattern
stands for (matches) any single character; a percent sign % matches any string of zero or
more characters.
9. Like matches field_name against the %value% pattern. Similar to =like but wraps value
with '%' before matching
10. not like doesn't match against the %value% pattern
11. Ilike case insensitive like
12. not ilike case insensitive not like
13. =ilike case insensitive =like
14. In is equal to any of the items from value, value should be a list of items
15. not in is unequal to all of the items from value
16. child_of is a child (descendant) of a value record.
17. Takes the semantics of the model into account (i.e following the relationship field named
by _parent_name).
131. • Value
variable type, must be comparable (through operator) to the named field
• Domain criteria can be combined using logical operators in prefix
form:
• & : logical AND, default operation to combine criteria following one
another. Arity 2 (uses the next 2 criteria or combinations).
• | : logical OR.
• ! : logical NOT.
132. Inheritance
• Odoo provides three different mechanisms to extend models in a modular way:
Classical inheritance :
When use (_inherit + _name) = the new model will use the existing model
Extension inheritance :
When use (_inherit) without (_name) in new model it will replace the existing one
Delegation inheritance :
The third inheritance mechanism provides more flexibility (it can be altered at
runtime) but less power: using the _inherits a model delegates the lookup of
any field not found on the current model to "children" models. The delegation
is performed via Reference fields automatically set up on the parent model.(in
this type only fields are inherited)