Parameters for fields constructor function in the context of Odoo13

The field descriptor contains the field definition, and manages accesses and assignments of the corresponding field on records.Odoo supports several fields for better data handling with specific options for each type.

The fields can be categorized into several types.

1. Basic Fields
2. Advanced Fields
       Date(time) Fields
       Relational Fields
       Pseudo-relational Fields
       Computed Fields
       Related Fields
3. Automatic Fields
4. Reserved Field names

Firstly, we need to import package fields.

    from odoo import models, fields

Basic Fields:

1. Boolean: to store boolean values True and False
Syntax:
 field_name = fields.Boolean(string=’Label for the field ’,optional parameter)
Example:
 is_company = fields.Boolean(string=”Is Company”, default=True)

2. Char: to store string or characters with length.
Parameter:
 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.

Example:
 name = fields.Char(string=”Name”, required=True, size=64)

3. Integer: to store integer values. Null value is not allowed. If there is no value then it returns zero.

Example:
 number = fields.Integer(string=’Number’,index=True)

4. Float: to store float values.Null value is not supported. If there is no value, it returns 0.0.
 Parameter:
digits (tuple(int,int) or str) – a pair (total, decimal) or a string referencing a decimal.precision record.it defines the precision and scale of the number. Scale is the number of digits after the decimal point and precision is the total number of significant digits in the number.

Example:
 amount = fields.Float(string=”Amount”, digits=(6, 3))

Advanced Fields:

1. Html: to stores HTML and used as HTML Widget.
Example:
 body = fields.Html(‘Activity Description’, readonly=True)

2. Monetary: the decimal precision and currency symbol are taken from the attribute.
Parameter:
 currency_field (str) – name of the field holding the currency this monetary field is expressed in (default: ‘currency_id’)
Example:
 total = fields.Monetary(string=’Total’,currency_field=’currency_id’)

3. Selection
Parameter:
 selection (list(tuple(str,str)) or callable or str) – specifies the possible values 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))) – when you are trying to inherit or extend a model if you want to add more possible values to an existing selection field you may use the selection_add keyword argument:

Example:
 select = fields.Selection([(‘a’, ‘A’)])
 select = fields.Selection(selection=[(‘a’, ‘A’)])
 select = fields.Selection(selection=’_function_name’)

 class TestModel(models.Model):
    _inherit = ‘test.model’
 type = fields.Selection(selection_add=[(‘b’, ‘B’), (‘c’, ‘C’)])

The attribute selection is mandatory except in the case of related or extended fields.

4. Text: to store long texts,does not have a size and usually displayed as a multiline text box.
Parameter:
 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.

Example:
 notes = fields.Text(string=’Description’)

Date(time) 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 object while to_datetime() will convert to a datetime.datetime.

1.Date: to stores date. The field has some helpers:
 context_today: Returns current day date string based on timezone
 today: Returns current system date string
 from_string: Returns datetime.date() from string
 to_string: Returns date string from datetime.date

Example:
 today = fields.Date.today()
 today = fields.Date.context_today(self)
 today = fields.Date.context_today(self,timestamp=datetime.datetime.now())
 today = fields.Date.from_string(fields.Date.today())
 today = fields.Date.to_string(datetime.datetime.today())

2.DateTime: to stores date and time in the same field. The field has some helpers.
 context_timestamp: Returns current day date string based on timezone
 now: Returns current system date string
 from_string: Returns datetime.date() from string
 to_string: Returns date string from datetime.date

Example:
 today=fields.Datetime.context_timestamp(self,timestamp=datetime.datetime.now())
 today=fields.Datetime.now()
 today=fields.Datetime.from_string(fields.Datetime.now())
 today=fields.Datetime.to_string(datetime.datetime.now())

Relational Fields:

1. Many2one: Associates this object to a parent object via this field.
Parameters
 comodel_name (str) – name of the target model Mandatory except for related or extended fields.
 domain – an optional domain to set on candidate values on the client side (domain or string)
 context (dict) – an optional context to use on the client side when handling that field
 ondelete (str) – what to do when the referred record is deleted; possible values are: ‘set null’, ‘restrict’, ‘cascade’
 auto_join (bool) – whether JOINs are generated upon search through that field (default: False)
 delegate (bool) – set it to True to make fields of the target model accessible from the current model (corresponds to _inherits)
 check_company (bool) – Mark the field to be verified in _check_company(). Add a default company domain depending on the field attributes.

Example:
 country_id = fields.Many2one (comodel_name=’res.country’,related=’move_id.company_id.country_id’)

2. One2many: to stores a relation against many rows of co-model
Parameters
 comodel_name (str) – name of the target model
 inverse_name (str) – name of the inverse Many2one field in comodel_name
 domain – an optional domain to set on candidate values on the client side (domain or string)
 context (dict) – an optional context to use on the client side when handling that field
 auto_join (bool) – whether JOINs are generated upon search through that field (default: False)
 limit (int) – optional limit to use upon read

Example:   
 tax_ids = fields.One2many(comodel_name=’account.tax’, inverse_name=tax_id)

3. Many2many: to stores multiple rows of a relation.
Parameters
 comodel_name – name of the target model (string) mandatory except in the case of related or extended fields
 relation (str) – optional name of the table that stores the relation in the database
 column1 (str) – optional name of the column referring to “these” records in the table relation
 column2 (str) – optional name of the column referring to “those” records in the table relation
 domain – an optional domain to set on candidate values on the client side (domain or string)
 context (dict) – an optional context to use on the client side when handling that field
 check_company (bool) – Mark the field to be verified in _check_company(). Add a default company domain depending on the field attributes.
 limit (int) – optional limit to use upon read

Example:
 tag_ids = fields.Many2many(string=”Tags”, comodel_name=’account.account.tag’, ondelete=’restrict’)

The attributes relation, column1 and column2 are optional. If not given, names are automatically generated from model names, provided model_name and comodel_name are different

Pseudo-relational Fields:

1. Reference: to store an arbitrary reference to a model and a row.

Example:
 resource_ref = fields.Reference(string=’Record’, selection=’_selection_target_model’,
            compute=’_compute_resource_ref’, inverse=’_set_resource_ref’)

2. Many2oneReference

Example:
 res_id = fields.Many2oneReference(string=’Related Document ID’, index=True, required=True, model_field=’res_model’)

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().

from odoo import api
total = fields.Float(compute=’_compute_total’)


@api.depends(‘value’, ‘tax’)
def _compute_total(self):
    for record in self:
        record.total = record.value + record.value * record.tax

dependencies can be dotted paths when using sub-fields:

@api.depends(line_ids.value)
def _compute_total(self):
    for record in self:
        record.total = sum(line.value for line in record.line_ids)

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.

searching on a computed field can also be enabled by setting the search parameter. The value is a method name returning a Search domains.
upper_name = field.Char(compute=’_compute_upper’, search=’_search_upper’)

def _search_upper(self,operator,value):
     If operator == ‘like’:
    operator = ‘ilike’
    return [(‘name’,’operator’,value)]

The search method is invoked when processing domains before doing an actual search on the model. It must return a domain equivalent to the condition: field operator value.

Computed fields are readonly by default. 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:

document = fields.Char(compute=’_get_document’, inverse=’_set_document’)

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:

Example:
 nickname = fields.Char(related=’user_id.partner_id.name’, store=True)

Automatic Fields:

1. id Identifier field
2. create_date Datetime
3. create_uid Many2one
4. write_date Datetime
5. write_uid Many2one

The Common Parameters:

help: Provide a description of how the field should be used.

ondelete: To handle deletions in a related record.

Values are: ‘restrict’, ‘no action’, ‘cascade’, ‘set null’, and ‘set default’.

readonly: If value = True, then the user cannot edit the field.

required: The value of this argument is True, then the field can’t be empty before saving.

size: Size of the field in the database can specify like character or integer.

string: Set label for the field.

translate: If the value is True, then the content of the field should be translated.

invisible: Hide fields from view if the value is 1.

relation: Used to refer another table. Most commonly used in related and function field types.

compute: used to call a function to get the value of the field. The value of the compute will be the name of a function.

Comments

: ".

Leave a Reply

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

© 2020 Zesty Beanz Pvt Ltd All Rights Reserved.