Computed fields and default values

Computed fields and default values

So far fields have been stored directly in and retrieved directly from the database. Fields can also be computed. In that case, the field's value is not retrieved from the database but computed on-the-fly by calling a method of the model.

To create a computed field, create a field and set its attribute compute to the name of a method. The computation method should simply set the value of the field to compute on every record in self.

Note :self is a collection

The object self is a recordset, i.e., an ordered collection of records. It supports the standard Python operations on collections, like len(self) and iter(self), plus extra set operations like recs1 + recs2.

Iterating over self gives the records one by one, where each record is itself a collection of size 1. You can access/assign fields on single records by using the dot notation, like record.name.

import random

from openerp import models, fields

class ComputedModel(models.Model):

    _name = 'test.computed'
    name = fields.Char(compute='_compute_name')
    @api.multi
    def _compute_name(self):
        for record in self:
            record.name = str(random.randint(1, 1e6))


Dependencies


The value of a computed field usually depends on the values of other fields on the computed record. The ORM expects the developer to specify those dependencies on the compute method with the decorator depends(). The given dependencies are used by the ORM to trigger the recomputation of the field whenever some of its dependencies have been modified:

from openerp import models, fields, api

class ComputedModel(models.Model):
    _name = 'test.computed'

    name = fields.Char(compute='_compute_name')
    value = fields.Integer()

    @api.depends('value')
    def _compute_name(self):
        for record in self:
            self.name = "Record with value %s"


Default values


Any field can be given a default value. In the field definition, add the option default=X where X is either a Python literal value (boolean, integer, float, string), or a function taking a recordset and returning a value:

name = fields.Char(default="Unknown")
user_id = fields.Many2one('res.users', default=lambda self: self.env.user)

Note

The object self.env gives access to request parameters and other useful things:

    self.env.cr or self._cr is the database cursor object; it is used for querying the database

    self.env.uid or self._uid is the current user's database id

    self.env.user is the current user's record

    self.env.context or self._context is the context dictionary

    self.env.ref(xml_id) returns the record corresponding to an XML id

    self.env[model_name] returns an instance of the given model









0 comments:

Copyright © 2013 SoftKul