orm Package

object Module

class openerp_proxy.orm.object.Object(service, object_name)[source]

Bases: openerp_proxy.utils.DirMixIn

Base class for all Objects

Provides simple interface to remote osv.osv objects:

erp = Client(...)
sale_obj = Object(erp, 'sale.order')
sale_obj.search([('state','not in',['done','cancel'])])

To create new instance - use get_object function, it implements all extensions magic, whic is highly used in this project

It is posible to create extension only to specific object. Example could be found in plugins/module_utils.py file.

client

Client instance, this object is relatedto

Return type:openerp_proxy.core.Client
columns_info

Reads information about fields available on model

create(vals, context=None)[source]

Create new record with vals

Also look at Odoo documentation for this method

Parameters:
  • vals (dict) – dictionary with values to be written to newly created record
  • context (dict) – context dictionary
Returns:

ID of newly created record

Return type:

int

name

Name of the object

Return type:str
read(ids, fields=None, context=None)[source]

Read fields for records with id in ids

Also look at Odoo documentation for this method

Parameters:
  • ids (int|list) – ID or list of IDs of records to read data for
  • fields (list) – list of field names to read. if not passed all fields will be read.
  • context (dict) – dictionary with extra context
Returns:

list of dictionaries with data had been read

Return type:

list

resolve_field_path(field)[source]

Resolves dot-separated field path to list of tuples (model, field_name, related_model)

Parameters:field (str) – dot-separated field path to resolve

For example:

sale_obj = client['sale.order']
sale_obj.resolve_field_path('partner_id.country_id.name')

will be resoved to:

[('sale.order', 'partner_id', 'res.partner'),
 ('res.partner', 'country_id', 'res.country'),
 ('res.country', 'name', False)]
search(args[, offset=0][, limit=None][, order=None][, count=False][, context=None])[source]

Search records by criteria.

Also look at Odoo documentation for this method

search_read(domain=None, fields=None, offset=0, limit=None, order=None, context=None)[source]

Search and read records specified by domain

Note that this method reads data in correct order

Also look at Odoo documentation

Returns:list of dictionaries with data had been read
Return type:list
service

Object service instance

stdcall_methods

Property that returns all methods of this object, that supports standard call

Returns:list with names of stdcall methods
Return type:list(str)

Unlink records specified by ids

Also look at Odoo documentation for this method

Parameters:ids (list) – list of IDs of records to be deleted
write(ids, vals, context=None)[source]

Write data in vals dictionary to records with ID in ids

For more info, look at odoo documentation for this method

Parameters:
  • ids (int|list) – ID or list of IDs of records to write data for
  • vals (dict) – dictinary with values to be written to database for records specified by ids
  • context (dict) – context dictionary
openerp_proxy.orm.object.get_object(client, name)[source]

Create new Object instance.

Parameters:
  • client (Client) – Client instance to bind this object to
  • name (str) – name of object. Ex. ‘sale.order’
Returns:

Created Object instance

Return type:

Object

cache Module

openerp_proxy.orm.cache.empty_cache(client)[source]

Create instance of empty cache for Record

Parameters:client (Client) – instance of Client to create cache for
Returns:instance of Cache class
Return type:Cache

Cache is dictionary-like object with structure like:

cache = {
    'product.product': {
        1: {
            'id': 1,
            'name': 'product1',
            'default_code': 'product1',
        },
    },
}
class openerp_proxy.orm.cache.Cache(client, *args, **kwargs)[source]

Bases: dict

Cache to be used for Record’s data.

This is root cache, which manages model local cache

cache[‘res.partner’] -> ObjectCache(‘res.partner’)

client

Access to Client instance this cache belongs to

class openerp_proxy.orm.cache.ObjectCache(root, obj, *args, **kwargs)[source]

Bases: dict

Cache for object / model data

Automatically generates empty data dicts for records requested. Also contains object context

cache_field(rid, ftype, field_name, value)[source]

This method impelment additional caching functionality, like caching related fields, and so...

Parameters:
  • rid (int) – Record ID
  • ftype (str) – field type
  • field_name (str) – name of field
  • value – value to cache for field
context

Return context instance related to this cache

get_ids_to_read(*fields)[source]

Return list of ids, that have no at least one of specified fields in cache

For example:

cache.get_ids_to_read('name', 'country_id', 'parent_id')

This code will traverse all record ids managed by this cache, and find those that have no at least one field in cache. This is highly useful in prefetching

parse_prefetch_fields(fields)[source]

Parse fields to be prefetched, sparating, cache’s object fields and related fields.

Used internaly

Parameters:fields (list) – list of fields to prefetch
Returns:returns tuple(prefetch_fields, related_fields), where prefetch_fields is list of fields, to be read for current object, and related_fields is dictionary of form: {'related.object': ['relatedfield1', 'relatedfield2.relatedfield']}
Return type:tuple
prefetch_fields(fields)[source]

Prefetch specified fields for this cache. Also, dot (”.”) may be used in field name to prefetch related fields:

cache.prefetch_fields(
    ['myfield1', 'myfields2_ids.relatedfield'])
Parameters:fields (list) – list of fields to prefetch
update_context(new_context)[source]

Updates or sets new context for thes ObjectCache instance

Parameters:new_context (dict) – context dictionary to update cached context with
Returns:updated context
update_keys(keys)[source]

Add new IDs to cache.

Parameters:keys (list) – list of new IDs to be added to cache
Returns:self
Return type:ObjectCache

record Module

This module contains classes and logic to handle operations on records

class openerp_proxy.orm.record.Record(obj, rid, cache=None, context=None)[source]

Bases: openerp_proxy.utils.DirMixIn

Base class for all Records

Do not use it to create record instances manualy. Use get_record function instead. It implements all extensions mangic

But class should be used for isinstance checks.

It is posible to create extensions of this class that will be binded only to specific Odoo objects

For example, if You need to extend all recrods of products, do something like this:

class MyProductRecord(Record):
    class Meta:
        object_name = 'product.product'

    def __init__(self, *args, **kwargs):
        super(MyProductRecord, self).__init__(*args, **kwargs)

        # to avoid double read, save once read value to record
        # instance
        self._sale_orders = None

    @property
    def sale_orders(self):
        ''' Sale orders related to curent product
        '''
        if self._sale_orders is None:
            so = self._client['sale.order']
            domain = [('order_line.product_id', '=', self.id)]
            self._sale_orders = so.search_records(
                                    domain, cache=self._cache)
        return self._sale_orders

And atfter this, next code is valid:

products = client['product.product'].search_records([])
products_so = products.filter(lambda p: bool(p.sale_orders))
products_so_gt_10 = products.filter(
    lambda p: len(p.sale_orders) > 10)

for product in products_so_gt_10:
    print("Product: %s" % product.default_code)
    for pso in product.sale_orders:
        print("     %s" % pso.name)
Parameters:
  • obj (Object) – instance of object this record is related to
  • rid (int) – ID of database record to fetch data from
  • cache (Cache) – Cache instance. (usualy generated by function empty_cache())
  • context (dict) – if specified, then cache’s context will be updated

Note, to create instance of cache call empty_cache

as_dict

Provides dictionary with record’s data in raw form

Return type:dict
context

Returns context to be used for thist record

copy(default=None, context=None)[source]

copy this record.

Parameters:
  • default (dict) – dictionary default values for new record (optional)
  • context (dict) – dictionary with context used to copy this record. (optional)
Returns:

Record instance for created record

Return type:

Record

Note about context: by default cache’s context will be used, and if some context will be passed to this method, new dict, which is combination of default context and passed context, will be passed to server.

get(field_name, default=None)[source]

Try to get field field_name, if if field name is not available return default value for it

if default is None and it is not possible to get field value, then raises KeyErro

Parameters:
  • field_name (str) – name of field to get value for
  • default – default value for case when no such field
Returns:

field value

Raises KeyError:
 

if cannot get field value

Note: This may be useful for code that expected to be working for different Odoo versions which have different database schemes.

id

Record ID

Return type:int
read(fields=None, context=None, multi=False)[source]

Rereads data for this record (or for al records in whole cache)

Parameters:
  • fields (list) – list of fields to be read (optional)
  • context (dict) – context to be passed to read (optional) does not midify record’s context
  • multi (bool) – if set to True, that data will be read for all records of this object in current cache (query).
Returns:

dict with data had been read

Return type:

dict

refresh()[source]

Reread data and clean-up the caches

Returns:self
Return type:Record
openerp_proxy.orm.record.RecordRelations

alias of Record

class openerp_proxy.orm.record.ObjectRecords(*args, **kwargs)[source]

Bases: openerp_proxy.orm.object.Object

Adds support to use records from Object classes

browse(*args, **kwargs)[source]

Aliase to read_records method. In most cases same as serverside browse (i mean server version 7.0)

model

Returns Record instance of model related to this object. Useful to get additional info on object.

model_name

Result of name_get called on object’s model

read_records(ids, fields=None, context=None, cache=None)[source]

Return instance or RecordList class, making available to work with data simpler

Parameters:
  • ids (int|list of int) – ID or list of IDS to read data for
  • fields (list) – list of fields to read (optional)
  • context (dict) – context to be passed to read. default=None
  • cache (Cache) – cache to use for records and record lists. Pass None to create new cache. default=None.
Returns:

Record instance if ids is int or RecordList instance if ids is list of ints

Return type:

Record|RecordList

For example:

>>> so_obj = db['sale.order']
>>> data = so_obj.read_records([1,2,3,4,5])
>>> for order in data:
        order.write({'note': 'order data is %s'%order.data})
search_records(*args, **kwargs)[source]

Return instance or list of instances of Record class, making available to work with data simpler

Parameters:
  • domain – list of tuples, specifying search domain
  • offset (int) – (optional) number of results to skip in the returned values (default:0)
  • limit (int|False) – optional max number of records in result (default: False)
  • order (str) – optional columns to sort
  • context (dict) – optional context to pass to search method
  • count – if set to True, then only amount of recrods found will be returned. (default: False)
  • read_fields (list of strings) – optional. specifies list of fields to read.
  • cache (Cache) – cache to be used for records and recordlists
Returns:

RecordList contains records found, or integer that represents amount of records found (if count=True)

Return type:

RecordList|int

For example:

>>> so_obj = db['sale.order']
>>> data = so_obj.search_records([('date','>=','2013-01-01')])
>>> for order in data:
...     order.write({'note': 'order date is %s'%order.date})
simple_fields

List of simple fields which could be fetched fast enough

This list contains all fields that are not function nor binary

Type:list of strings
class openerp_proxy.orm.record.RecordList(obj, ids=None, fields=None, cache=None, context=None)[source]

Bases: _abcoll.MutableSequence, openerp_proxy.utils.DirMixIn

Class to hold list of records with some extra functionality

Parameters:
  • obj (Object) – instance of Object to make this list related to
  • ids (list of int) – list of IDs of objects to read data from
  • fields (list of strings) – list of field names to read by default
  • cache (Cache) – Cache instance. (usualy generated by function empty_cache()
  • context (dict) – context to be passed automatically to methods called from this list (not used yet)
context

Returns context to be used for this list

copy(context=None, new_cache=False)[source]

Returns copy of this list, possibly with modified context and new empty cache.

Parameters:
  • context (dict) – new context values to be used on new list
  • new_cache (bool) – if set to True, then new cache instance will be created for resulting recordlist if set to Cache instance, than it will be used for resulting recordlist
Returns:

copy of this record list.

Return type:

RecordList

Raises ValueError:
 

when incorrect value passed to new_cache

existing(uniqify=True)[source]

Filters this list with only existing items

Parm bool uniqify:
 if set to True, then all dublicates will be removed. Default: True
Returns:new RecordList instance
Return type:RecordList
filter(func)[source]

Filters items using func.

Parameters:func (callable(record)->bool|anyfield.SField) – callable to check if record should be included in result.
Returns:RecordList which contains records that matches results
Return type:RecordList
group_by(grouper)[source]

Groups all records in list by specifed grouper.

Parameters:grouper (string|callable(record)|anyfield.SField) – field name or callable to group results by. if callable is passed, it should receive only one argument - record instance, and result of calling grouper will be used as key to group records by.
Returns:dictionary

for example we have list of sale orders and want to group it by state

# so_list - variable that contains list of sale orders selected
# by some criterias. so to group it by state we will do:
group = so_list.group_by('state')

# Iterate over resulting dictionary
for state, rlist in group.iteritems():
    # Print state and amount of items with such state
    print state, rlist.length

or imagine that we would like to group records by last letter of sale order number

# so_list - variable that contains list of sale orders selected
# by some criterias. so to group it by last letter of sale
# order name  we will do:
group = so_list.group_by(lambda so: so.name[-1])

# Iterate over resulting dictionary
for letter, rlist in group.iteritems():
    # Print state and amount of items with such state
    print letter, rlist.length
ids

IDs of records present in this RecordList

insert(index, item)[source]

Insert record to list

Parameters:
  • item (Record|int) – Record instance to be inserted into list. if int passed, it considered to be ID of record
  • index (int) – position where to place new element
Returns:

self

Return type:

RecordList

length

Returns length of this record list

mapped(field)[source]

Experimental, Provides similar functionality to Odoo’s mapped() method, but supports only dot-separated field name as argument, no callables yet.

Returns list of values of field of each record in this recordlist. If value of field is RecordList or Record instance, than RecordList instance will be returned

Thus folowing code will work

# returns a list of names
records.mapped('name')

# returns a recordset of partners
record.mapped('partner_id')

# returns the union of all partner banks,
# with duplicates removed
record.mapped('partner_id.bank_ids')
Parameters:field (str) – returns list of values of ‘field’ for each record in this RecordList
Return type:list or RecordList
object

Object this record is related to

prefetch(*fields)[source]

Prefetches specified fields into cache if no fields passed, then all ‘simple_fields’ will be prefetched

By default field read performed only when that field is requested, thus when You need to read more then one field, few rpc requests will be performed. to avoid multiple unneccessary rpc calls this method is implemented.

Returns:self, which allows chaining of operations
Return type:RecordList
read(fields=None, context=None)[source]

Read wrapper. Takes care about adding RecordList’s context to object’s read method.

Warning: does not update cache by data been read

records

Returns list (class ‘list’) of records

refresh()[source]

Cleanup data caches. next try to get data will cause rereading of it

Returns:self
Return type:instance of RecordList
search(domain, *args, **kwargs)[source]

Performs normal search, but adds ('id', 'in', self.ids) to search domain

Returns:list of IDs found
Return type:list of integers
search_records(domain, *args, **kwargs)[source]

Performs normal search_records, but adds ('id', 'in', self.ids) to domain

Returns:RecordList of records found
Return type:RecordList instance
sort(key=None, reverse=False)[source]

sort(key=None, reverse=False) – inplace sort

anyfield.SField instances may be safely passed as ‘key’ arguments. no need to convert them to function explicitly

Returns:self
openerp_proxy.orm.record.get_record(obj, rid, cache=None, context=None)[source]

Creates new Record instance

Use this method to create new records, because of standard object creation bypasses extension’s magic.

param Object obj:
 instance of Object this record is related to
param int rid:ID of database record to fetch data from
param cache:Cache instance. (usualy generated by function empty_cache()
type cache:Cache
param dict context:
 if specified, then cache’s context will be updated
return:created Record instance
rtype:Record
openerp_proxy.orm.record.get_record_list(obj, ids=None, fields=None, cache=None, context=None)[source]

Returns new instance of RecordList object.

Parameters:
  • obj (Object) – instance of Object to make this list related to
  • ids (list of int) – list of IDs of objects to read data from
  • fields (list of strings (not used now)) – list of field names to read by default (not used now)
  • cache (Cache) – Cache instance. (usualy generated by function empty_cache()
  • context (dict) – context to be passed automatically to methods called from this list (not used yet)

service Module

class openerp_proxy.orm.service.Service(*args, **kwargs)[source]

Bases: openerp_proxy.service.object.ObjectService

Service class to simplify interaction with ‘object’ service. Particulary, implements logic of choosing execute method (‘execute’ or ‘execute_kw’) to use. The last one cannot work with keyword arguments

clean_cache()[source]

Cleans caches, to fill them with fresh data on next call of related methods

get_obj(object_name)[source]

Returns wraper around Odoo object ‘object_name’ which is instance of Object

Parameters:object_name (string) – name of an object to get wraper for
Returns:instance of Object which wraps choosen object
Return type:Object