0% found this document useful (0 votes)
511 views1 page

ORM API - Odoo 13.0 Documentation

The document discusses Odoo's object relational mapping module and model fields. It describes how models are defined by inheriting BaseModel and the types of fields that can be defined on models. It also provides the API documentation for BaseModel and summaries of Model, TransientModel, AbstractModel, and Field classes.

Uploaded by

Cristian Salamea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
511 views1 page

ORM API - Odoo 13.0 Documentation

The document discusses Odoo's object relational mapping module and model fields. It describes how models are defined by inheriting BaseModel and the types of fields that can be defined on models. It also provides the API documentation for BaseModel and summaries of Model, TransientModel, AbstractModel, and Field classes.

Uploaded by

Cristian Salamea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

$

Navigate %

Object Relational Mapping module:


Hierarchical structure
Constraints consistency and validation
Object metadata depends on its status
Optimised processing by complex query
(multiple actions at once)
Default field values
Permissions optimisation
Persistent object: DB postgresql
Data conversion
Multi-level caching system
Two different inheritance mechanisms
Rich set of field types:
classical (varchar, integer, boolean,
…)
relational (one2many, many2one,
many2many)
functional

Models
Model fields are defined as attributes on the
model itself:

from odoo import models, fields


class AModel(models.Model):
_name = 'a.model.name'

field1 = fields.Char()

! Warning
this means you cannot define a field and a
method with the same name, the last one will
silently overwrite the former ones.

By default, the field’s label (user-visible name)


is a capitalized version of the field name, this
can be overridden with the string parameter.

field2 = fields.Integer(string="Field Lab


el")

For the list of field types and parameters, see


the fields reference.

Default values are defined as parameters on


fields, either as a value:

name = fields.Char(default="a value")

or as a function called to compute the default


value, which should return that value:

def _default_name(self):
return self.get_value()

name = fields.Char(default=lambda self: s


elf._default_name())

API
class odoo.models.BaseModel
Base class for Odoo models.

Odoo models are created by inheriting one


of the following:

Model for regular database-persisted


models
TransientModel for temporary data,
stored in the database but automatically
vacuumed every so often
AbstractModel for abstract super
classes meant to be shared by multiple
inheriting models

The system automatically instantiates every


model once per database. Those instances
represent the available models on each
database, and depend on which modules are
installed on that database. The actual class
of each instance is built from the Python
classes that create and inherit from the
corresponding model.

Every model instance is a “recordset”, i.e., an


ordered collection of records of the model.
Recordsets are returned by methods like
browse() , search() , or field accesses.
Records have no explicit representation: a
record is represented as a recordset of one
record.

To create a class that should not be


instantiated, the _register attribute may be
set to False.

_auto = False
Whether a database table should be
created (default: True ). If set to False ,
override init() to create the database
table.

To create a model without any table,


inherit from AbstractModel .

_table = None
SQL table name used by model if _auto

_sequence = None
SQL sequence to use for ID field

_sql_constraints = []
SQL constraints [(name, sql_def,
message)]

_register = True
not visible in ORM registry

_name = None
the model name (in dot-notation, module
namespace)

_description = None
the model’s informal name

_inherit = None
Python-inherited models:

Type:

str or list(str)

If _name is set, name(s) of parent


models to inherit from
If _name is unset, name of a single
model to extend in-place

_inherits = {}
dictionary {‘parent_model’: ‘m2o_field’}
mapping the _name of the parent
business objects to the names of the
corresponding foreign key fields to use:

_inherits = {
'a.model': 'a_field_id',
'b.model': 'b_field_id'
}

implements composition-based
inheritance: the new model exposes all
the fields of the inherited models but
stores none of them: the values
themselves remain stored on the linked
record.

! Warning
if multiple fields with the same name are
defined in the _inherits -ed models, the
inherited field will correspond to the last
one (in the inherits list order).

_rec_name = None
field to use for labeling records, default:
name

_order = 'id'
default order field for searching results

_check_company_auto = False
On write and create, call _check_company
to ensure companies consistency on the
relational fields having
check_company=True as attribute.

_parent_name = 'parent_id'
the many2one field used as parent field

_parent_store = False
set to True to compute parent_path field.

Alongside a parent_path field, sets up an


indexed storage of the tree structure of
records, to enable faster hierarchical
queries on the records of the current
model using the child_of and parent_of
domain operators.

_abstract = True
whether model is abstract

" See also


odoo.models.AbstractModel

_transient = False
whether model is transient

" See also


odoo.models.TransientModel

_date_name = 'date'
field to use for default calendar view

_fold_name = 'fold'
field to determine folded groups in
kanban views

AbstractModel
odoo.models.AbstractModel
alias of odoo.models.BaseModel

Model
class odoo.models.Model
Main super-class for regular database-
persisted Odoo models.

Odoo models are created by inheriting from


this class:

class user(Model):
...

The system will later instantiate the class


once per database (on which the class’
module is installed).

TransientModel
class odoo.models.TransientModel
Model super-class for transient records,
meant to be temporarily persistent, and
regularly vacuum-cleaned.

A TransientModel has a simplified access


rights management, all users can create new
records, and may only access the records
they created. The superuser has
unrestricted access to all TransientModel
records.

Fields
class odoo.fields.Field
The field descriptor contains the field
definition, and manages accesses and
assignments of the corresponding field on
records. The following attributes may be
provided when instanciating a field:

Parameters:

string ( str ) – the label of the field seen by users; if not set, the
ORM takes the field name in the class (capitalized).

help ( str ) – the tooltip of the field seen by users

readonly ( bool ) –
whether the field is readonly (default: False )
This only has an impact on the UI. Any field assignation in code will
work (if the field is a stored field or an inversable one).

required ( bool ) – whether the value of the field is required


(default: False )

index ( bool ) – whether the field is indexed in database. Note: no


effect on non-stored and virtual fields. (default: False )

default ( value or callable ) – 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 ( dict ) –
a dictionary mapping state values to lists of UI attribute-value pairs;
possible attributes are: readonly , required , invisible .

! Warning
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.

groups ( str ) – comma-separated list of group xml ids (string); this


restricts the field access to the users of the given groups only

company_dependent ( bool ) –
whether the field value is dependent of the current company;
The value isn’t stored on the model table. It is registered as
ir.property . When the value of the company_dependent field is
needed, an ir.property is searched, linked to the current company
(and current record if one property exists).
If the value is changed on the record, it either modifies the existing
property for the current record (if one exists), or creates a new one
for the current company and res_id.
If the value is changed on the company side, it will impact all records
on which the value hasn’t been changed.

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)

store ( bool ) – whether the field is stored in database


(default: True , False for computed fields)

group_operator ( str ) –
aggregate function used by read_group() when grouping on this
field.
Supported aggregate functions are:
array_agg : values, including nulls, concatenated into an array

count : number of rows

count_distinct : number of distinct rows

bool_and : true if all values are true, otherwise false

bool_or : true if at least one value is true, otherwise false

max : maximum value of all values

min : minimum value of all values

avg : the average (arithmetic mean) of all values

sum : sum of all values

group_expand ( str ) –
function used to expand read_group results when grouping on the
current field.

@api.model
def _read_group_selection_field(self, values, domain, order):
return ['choice1', 'choice2', ...] # available selection choi
ces.

@api.model
def _read_group_many2one_field(self, records, domain, order):
return records + self.search([custom_domain])

Computed Fields
Parameters:

compute ( str ) –
name of a method that computes the field

" See also


Advanced Fields/Compute fields

compute_sudo ( bool ) – whether the field


should be recomputed as superuser to bypass
access rights (by default True for stored fields,
False for non stored fields)

inverse ( str ) – name of a method that


inverses the field (optional)

search ( str ) – name of a method that


implement search on the field (optional)

related ( str ) –
sequence of field names

" See also


Advanced fields/Related fields

Basic Fields
class odoo.fields.Boolean
Encapsulates a bool .

class odoo.fields.Char
Basic string field, can be length-limited,
usually displayed as a single-line string in
clients.

Parameters:

size ( int ) – the maximum size of values stored


for that field

trim ( bool ) – states whether the value is


trimmed or not (by default, True ). Note that the
trim operation is applied only by the web client.

translate ( bool or callable ) – enable the


translation of the field’s values; use
translate=True to translate field values as a
whole; translate may also be a callable such
that translate(callback, value) translates
value by using callback(term) to retrieve the
translation of terms.

class odoo.fields.Float
Encapsulates a float .

The precision digits are given by the


(optional) digits attribute.

Parameters:

digits ( tuple ( int , int ) or str ) – a pair

(total, decimal) or a string referencing a

DecimalPrecision record name.

class odoo.fields.Integer
Encapsulates an int .

Advanced Fields
class odoo.fields.Binary
Encapsulates a binary content (e.g. a file).

Parameters:

attachment ( bool ) – whether the field should

be stored as ir_attachment or in a column of the

model’s table (default: True ).

class odoo.fields.Html
Encapsulates an html code content.

Parameters:

sanitize ( bool ) – whether value must be


sanitized (default: True )

sanitize_tags ( bool ) – whether to sanitize


tags (only a white list of attributes is accepted,
default: True )

sanitize_attributes ( bool ) – whether to


sanitize attributes (only a white list of attributes
is accepted, default: True )

sanitize_style ( bool ) – whether to sanitize


style attributes (default: True )

strip_style ( bool ) – whether to strip style


attributes (removed and therefore not sanitized,
default: False )

strip_classes ( bool ) – whether to strip


classes attributes (default: False )

class odoo.fields.Image
Encapsulates an image, extending Binary .

If image size is greater than the


max_width / max_height limit of pixels, the
image will be resized to the limit by keeping
aspect ratio.

Parameters:

max_width ( int ) – the maximum width of the


image (default: 0 , no limit)

max_height ( int ) – the maximum height of the


image (default: 0 , no limit)

verify_resolution ( bool ) – whether the


image resolution should be verified to ensure it
doesn’t go over the maximum image resolution
(default: True ). See
odoo.tools.image.ImageProcess for maximum
image resolution (default: 45e6 ).

If no max_width / max_height is specified (or is


set to 0) and verify_resolution is False, the
field content won’t be verified at all and a
Binary field should be used.

class odoo.fields.Monetary
Encapsulates a float expressed in a given
res_currency .

The decimal precision and currency symbol


are taken from the currency_field attribute.

Parameters:

currency_field ( str ) – name of the Many2one

field holding the res_currency this monetary field

is expressed in (default: 'currency_id' )

class odoo.fields.Selection
Encapsulates an exclusive choice between
different values.

Parameters:

selection ( list ( tuple ( str , str ) ) or


callable or ) – specifies the possible values
str
for this field. It is given as either a list of pairs
(value, label) , or a model method, or a method
name.

selection_add
( list ( tuple ( str , str ) ) ) –
provides an extension of the selection in the case
of an overridden field. It is a list of pairs (value,
label) or singletons (value,) , where singleton
values must appear in the overridden selection.
The new values are inserted in an order that is
consistent with the overridden selection and this
list:

selection = [('a', 'A'), ('b', 'B')]


selection_add = [('c', 'C'), ('b',)]
> result = [('a', 'A'), ('c', 'C'), ('b', 'B')]

The attribute selection is mandatory


except in the case of related or extended
fields.

class odoo.fields.Text
Very similar to Char but used for longer
contents, does not have a size and usually
displayed as a multiline text box.

Parameters:

translate ( bool or callable ) – enable the

translation of the field’s values; use

translate=True to translate field values as a

whole; translate may also be a callable such

that translate(callback, value) translates

value by using callback(term) to retrieve the

translation of terms.

Date(time) Fields
Dates and Datetimes are very important fields
in any kind of business application. Their
misuse can create invisible yet painful bugs,
this section aims to provide Odoo developers
with the knowledge required to avoid misusing
these fields.

When assigning a value to a Date/Datetime


field, the following options are valid:

A date or datetime object.

A string in the proper server format:


YYYY-MM-DD for Date fields,

YYYY-MM-DD HH:MM:SS for Datetime


fields.
False or None .

The Date and Datetime fields class have helper


methods to attempt conversion into a
compatible type:

to_date() will convert to a datetime.date

to_datetime() will convert to a


datetime.datetime .

# Example
To parse date/datetimes coming from external
sources:

fields.Date.to_date(self._context.get('date
_from'))

Date / Datetime comparison best practices:

Date fields can only be compared to date


objects.
Datetime fields can only be compared to
datetime objects.

! Warning
Strings representing dates and datetimes can
be compared between each other, however the
result may not be the expected result, as a
datetime string will always be greater than a
date string, therefore this practice is heavily
discouraged.

Common operations with dates and datetimes


such as addition, substraction or fetching the
start/end of a period are exposed through both
Date and Datetime . These helpers are also
available by importing odoo.tools.date_utils .

Timezones
Datetime fields are stored as timestamp without
timezone columns in the database and are
stored in the UTC timezone. This is by design,
as it makes the Odoo database independent
from the timezone of the hosting server system.
Timezone conversion is managed entirely by the
client side.

class odoo.fields.Date
Encapsulates a python date object.

static add(*args, **kwargs)


Return the sum of value and a
relativedelta .

Parameters:
value – initial date or datetime.

args – positional args to pass directly to


relativedelta .

kwargs – keyword args to pass directly to


relativedelta .

Returns:

the resulting date/datetime.

static context_today(timestamp=None)
Return the current date as seen in the
client’s timezone in a format fit for date
fields.

This method may be used to compute


default values.

Parameters:
record – recordset from which the timezone
will be obtained.

timestamp ( datetime ) – optional datetime


value to use instead of the current date and
time (must be a datetime, regular dates can’t
be converted between timezones).

Return type:

date

static end_of(granularity)
Get end of a time period from a date or a
datetime.

Parameters:
value – initial date or datetime.

granularity – Type of period in string, can

You might also like