Sunday, 21 September 2014

Odoo New API: Active Record Pattern


Share it Please

Active Record:

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Active Record Pattern:

The active record pattern is an approach to accessing data in a database. A database table is wrapped into a class.

In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database.

One of the new feature introduced in new API is a support for the active record pattern.


def method(self):
    for record in self: = 'blah'
This will simply writes the value to database.

Implementation Detail:

With the help of special methods:

1. __iter__(self):
    Return an iterator over 'self'.

2. __getitem__(self, key):

    If 'key' is an integer or a slice, return the corresponding record
    selection as an instance (attached to 'self.env').
    Otherwise read the field 'key' of the first record in 'self'.


        inst =    # inst is a recordset
        r4 = inst[3]                           # fourth record in inst
        rs = inst[10:20]                    # subset of inst
        nm = rs['name']                   # name of first record in inst

3. __setitem__(self, key, value):

    - Assign the field 'key' to 'value' in record 'self'.
    - It also calls the field's setter, to simply write to the database, and update cache.

Be Careful:

It is very expensive to use Active Record Pattern while writing the value. As Each assignment will trigger a write action on the database.

def method(self):
    self.a = 1
    self.b = 7
    self.c = 8

On above example each assignment will trigger a write on the database. As the function is decorated with for each record in  recordset write will be called 3 times. So if you have 'n' numbers of records in recordset, the number of writes will be n*3.

This may leads to performance bottleneck on heavy task. In that case it is better to use:

def method(self):
    for record in self:
        record.write({'a': 1, 'b': 7, 'c': 8})
or, if you want to write same value on all the records then it is more better to use:

def method(self):
    self.write({'a':1, 'b': 7, 'c': 8})


Post a Comment