1 Objects, Fields and Methods
2 ===========================
7 .. This chapter is dedicated to detailed objects definition:
12 All the ERP's pieces of data are accessible through "objects". As an example, there is a res.partner object to access the data concerning the partners, an account.invoice object for the data concerning the invoices, etc...
14 Please note that there is an object for every type of resource, and not an
15 object per resource. We have thus a res.partner object to manage all the
16 partners and not a *res.partner* object per partner. If we talk in "object
17 oriented" terms, we could also say that there is an object per level.
19 The direct consequences is that all the methods of objects have a common parameter: the "ids" parameter. This specifies on which resources (for example, on which partner) the method must be applied. Precisely, this parameter contains a list of resource ids on which the method must be applied.
21 For example, if we have two partners with the identifiers 1 and 5, and we want to call the res_partner method "send_email", we will write something like::
23 res_partner.send_email(... , [1, 5], ...)
25 We will see the exact syntax of object method calls further in this document.
27 In the following section, we will see how to define a new object. Then, we will check out the different methods of doing this.
31 * OpenERP "objects" are usually called classes in object oriented programming.
32 * A OpenERP "resource" is usually called an object in OO programming, instance of a class.
34 It's a bit confusing when you try to program inside OpenERP, because the language used is Python, and Python is a fully object oriented language, and has objects and instances ...
36 Luckily, an OpenERP "resource" can be converted magically into a nice Python object using the "browse" class method (OpenERP object method).
39 The ORM - Object-relational mapping - Models
40 --------------------------------------------
42 The ORM, short for Object-Relational Mapping, is a central part of OpenERP.
44 In OpenERP, the data model is described and manipulated through Python classes
45 and objects. It is the ORM job to bridge the gap -- as transparently as
46 possible for the developer -- between Python and the underlying relational
47 database (PostgreSQL), which will provide the persistence we need for our
51 OpenERP Object Attributes
52 -------------------------
57 To define a new object, you must define a new Python class then instantiate it. This class must inherit from the osv class in the osv module.
62 The first line of the object definition will always be of the form::
64 class name_of_the_object(osv.osv):
65 _name = 'name.of.the.object'
70 An object is defined by declaring some fields with predefined names in the
71 class. Two of them are required (_name and _columns), the rest are optional.
72 The predefined fields are:
78 Determines whether a corresponding PostgreSQL table must be generated
79 automatically from the object. Setting _auto to False can be useful in case
80 of OpenERP objects generated from PostgreSQL views. See the "Reporting From
81 PostgreSQL Views" section for more details.
84 The object fields. See the :ref:`fields <fields-link>` section for further details.
87 The constraints on the object. See the constraints section for details.
90 The SQL Constraint on the object. See the SQL constraints section for further details.
93 The default values for some of the object's fields. See the default value section for details.
96 The name of the osv object which the current object inherits from. See the :ref:`object inheritance section<inherit-link>`
97 (first form) for further details.
100 The list of osv objects the object inherits from. This list must be given in
101 a python dictionary of the form: {'name_of_the_parent_object':
102 'name_of_the_field', ...}. See the :ref:`object inheritance section<inherits-link>`
103 (second form) for further details. Default value: {}.
106 Determines whether or not the write access to the resource must be logged.
107 If true, four fields will be created in the SQL table: create_uid,
108 create_date, write_uid, write_date. Those fields represent respectively the
109 id of the user who created the record, the creation date of record, the id
110 of the user who last modified the record, and the date of that last
111 modification. This data may be obtained by using the perm_read method.
114 Name of the object. Default value: None.
117 Name of the fields used to sort the results of the search and read methods.
124 _order = "date_order desc"
127 Name of the field in which the name of every resource is stored. Default
128 value: 'name'. Note: by default, the name_get method simply returns the
129 content of this field.
132 Name of the SQL sequence that manages the ids for this object. Default value: None.
135 SQL code executed upon creation of the object (only if _auto is True). It means this code gets executed after the table is created.
138 Name of the SQL table. Default value: the value of the _name field above
139 with the dots ( . ) replaced by underscores ( _ ).
144 Object Inheritance - _inherit
145 -----------------------------
150 Objects may be inherited in some custom or specific modules. It is better to
151 inherit an object to add/modify some fields.
155 _inherit='object.name'
157 Extension of an object
158 ++++++++++++++++++++++
160 There are two possible ways to do this kind of inheritance. Both ways result in
161 a new class of data, which holds parent fields and behaviour as well as
162 additional fields and behaviour, but they differ in heavy programatical
165 While Example 1 creates a new subclass "custom_material" that may be "seen" or
166 "used" by any view or tree which handles "network.material", this will not be
167 the case for Example 2.
169 This is due to the table (other.material) the new subclass is operating on,
170 which will never be recognized by previous "network.material" views or trees.
174 class custom_material(osv.osv):
175 _name = 'network.material'
176 _inherit = 'network.material'
178 'manuf_warranty': fields.boolean('Manufacturer warranty?'),
181 'manuf_warranty': lambda *a: False,
189 In this example, the 'custom_material' will add a new field 'manuf_warranty' to
190 the object 'network.material'. New instances of this class will be visible by
191 views or trees operating on the superclasses table 'network.material'.
193 This inheritancy is usually called "class inheritance" in Object oriented
194 design. The child inherits data (fields) and behavior (functions) of his
200 class other_material(osv.osv):
201 _name = 'other.material'
202 _inherit = 'network.material'
204 'manuf_warranty': fields.boolean('Manufacturer warranty?'),
207 'manuf_warranty': lambda *a: False,
215 In this example, the 'other_material' will hold all fields specified by
216 'network.material' and it will additionally hold a new field 'manuf_warranty'.
217 All those fields will be part of the table 'other.material'. New instances of
218 this class will therefore never been seen by views or trees operating on the
219 superclasses table 'network.material'.
221 This type of inheritancy is known as "inheritance by prototyping" (e.g.
222 Javascript), because the newly created subclass "copies" all fields from the
223 specified superclass (prototype). The child inherits data (fields) and behavior
224 (functions) of his parent.
229 Inheritance by Delegation - _inherits
230 -------------------------------------
234 class tiny_object(osv.osv)
235 _name = 'tiny.object'
236 _table = 'tiny_object'
238 'tiny.object_a': 'object_a_id',
239 'tiny.object_b': 'object_b_id',
241 'tiny.object_n': 'object_n_id'
245 The object 'tiny.object' inherits from all the columns and all the methods from
246 the n objects 'tiny.object_a', ..., 'tiny.object_n'.
248 To inherit from multiple tables, the technique consists in adding one column to
249 the table tiny_object per inherited object. This column will store a foreign
250 key (an id from another table). The values *'object_a_id' 'object_b_id' ...
251 'object_n_id'* are of type string and determine the title of the columns in
252 which the foreign keys from 'tiny.object_a', ..., 'tiny.object_n' are stored.
254 This inheritance mechanism is usually called " *instance inheritance* " or "
255 *value inheritance* ". A resource (instance) has the VALUES of its parents.
263 Objects may contain different types of fields. Those types can be divided into
264 three categories: simple types, relation types and functional fields. The
265 simple types are integers, floats, booleans, strings, etc ... ; the relation
266 types are used to represent relations between objects (one2one, one2many,
267 many2one). Functional fields are special fields because they are not stored in
268 the database but calculated in real time given other fields of the view.
270 Here's the header of the initialization method of the class any field defined
271 in OpenERP inherits (as you can see in server/bin/osv/fields.py)::
273 def __init__(self, string='unknown', required=False, readonly=False,
274 domain=None, context="", states=None, priority=0, change_default=False, size=None,
275 ondelete="set null", translate=False, select=False, **args) :
277 There are a common set of optional parameters that are available to most field
281 Whether or not the user can define default values on other fields depending
282 on the value of this field. Those default values need to be defined in
285 A description of how the field should be used: longer and more descriptive
286 than `string`. It will appear in a tooltip when the mouse hovers over the
289 How to handle deletions in a related record. Allowable values are:
290 'restrict', 'no action', 'cascade', 'set null', and 'set default'.
292 :readonly: `True` if the user cannot edit this field, otherwise `False`.
294 `True` if this field must have a value before the object can be saved,
296 :size: The size of the field in the database: number characters or digits.
298 Lets you override other parameters for specific states of this object.
299 Accepts a dictionary with the state names as keys and a list of name/value
300 tuples as the values. For example: `states={'posted':[('readonly',True)]}`
302 The field name as it should appear in a label or column header. Strings
303 containing non-ASCII characters must use python unicode objects.
304 For example: `'tested': fields.boolean(u'Testé')`
306 `True` if the *content* of this field should be translated, otherwise
309 There are also some optional parameters that are specific to some field types:
312 Define a variable's value visible in the view's context or an on-change
313 function. Used when searching child table of `one2many` relationship?
315 Domain restriction on a relational field.
319 Example: domain=[('field','=',value)])
320 :invisible: Hide the field's value in forms. For example, a password.
322 Default value for the `on_change` attribute in the view. This will launch
323 a function on the server when the field changes in the client. For example,
324 `on_change="onchange_shop_id(shop_id)"`.
326 Used when a field is an id reference to another table. This is the name of
327 the table to look in. Most commonly used with related and function field
330 Default value for the `select` attribute in the view. 1 means basic search,
331 and 2 means advanced search.
342 A boolean (true, false).
346 fields.boolean('Field Name' [, Optional Parameters]),
354 fields.integer('Field Name' [, Optional Parameters]),
358 A floating point number.
362 fields.float('Field Name' [, Optional Parameters]),
366 The optional parameter digits defines the precision and scale of the
367 number. The scale being the number of digits after the decimal point
368 whereas the precision is the total number of significant digits in the
369 number (before and after the decimal point). If the parameter digits is
370 not present, the number will be a double precision floating point number.
371 Warning: these floating-point numbers are inexact (not any value can be
372 converted to its binary representation) and this can lead to rounding
373 errors. You should always use the digits parameter for monetary amounts.
377 'rate': fields.float(
378 'Relative Change rate',
380 Optional Parameters]),
384 A string of limited length. The required size parameter determines its size.
391 Optional Parameters]), # where ''n'' is an integer.
395 'city' : fields.char('City Name', size=30, required=True),
399 A text field with no limit in length.
403 fields.text('Field Name' [, Optional Parameters]),
411 fields.date('Field Name' [, Optional Parameters]),
415 Allows to store a date and the time of day in the same field.
419 fields.datetime('Field Name' [, Optional Parameters]),
427 A field which allows the user to make a selection between various predefined values.
431 fields.selection((('n','Unconfirmed'), ('c','Confirmed')),
432 'Field Name' [, Optional Parameters]),
436 Format of the selection parameter: tuple of tuples of strings of the form::
438 (('key_or_value', 'string_to_display'), ... )
441 You can specify a function that will return the tuple. Example ::
443 def _get_selection(self, cursor, user_id, context=None):
445 ('choice1', 'This is the choice 1'),
446 ('choice2', 'This is the choice 2'))
449 'sel' : fields.selection(
451 'What do you want ?')
456 Using relation fields **many2one** with **selection**. In fields definitions add::
459 'my_field': fields.many2one(
460 'mymodule.relation.model',
462 selection=_sel_func),
465 And then define the _sel_func like this (but before the fields definitions)::
467 def _sel_func(self, cr, uid, context=None):
468 obj = self.pool.get('mymodule.relation.model')
469 ids = obj.search(cr, uid, [])
470 res = obj.read(cr, uid, ids, ['name', 'id'], context)
471 res = [(r['id'], r['name']) for r in res]
479 A one2one field expresses a one:to:one relation between two objects. It is
480 deprecated. Use many2one instead.
484 fields.one2one('other.object.name', 'Field Name')
488 Associates this object to a parent object via this Field. For example
489 Department an Employee belongs to would Many to one. i.e Many employees will
490 belong to a Department
501 - ondelete: What should happen when the resource this field points to is deleted.
502 + Predefined value: "cascade", "set null", "restrict", "no action", "set default"
503 + Default value: "set null"
506 - select: True - (creates an index on the Foreign Key field)
510 'commercial': fields.many2one(
528 - invisible: True/False
530 - readonly: True/False
534 'address': fields.one2many(
535 'res.partner.address',
545 fields.many2many('other.object.name',
552 - other.object.name is the other object which belongs to the relation
553 - relation object is the table that makes the link
554 - actual.object.id and other.object.id are the fields' names used in the relation table
560 'res.partner.category',
561 'res_partner_category_rel',
566 To make it bidirectional (= create a field in the other object)::
568 class other_object_name2(osv.osv):
569 _inherit = 'other.object.name'
571 'other_fields': fields.many2many(
572 'actual.object.name',
582 class res_partner_category2(osv.osv):
583 _inherit = 'res.partner.category'
585 'partner_ids': fields.many2many(
587 'res_partner_category_rel',
592 res_partner_category2()
596 Sometimes you need to refer to the relation of a relation. For example,
597 supposing you have objects: City -> State -> Country, and you need to refer to
598 the Country from a City, you can define a field as below in the City object::
600 'country_id': fields.related(
604 relation="res.country",
609 - The first set of parameters are the chain of reference fields to
610 follow, with the desired field at the end.
611 - :guilabel:`type` is the type of that desired field.
612 - Use :guilabel:`relation` if the desired field is still some kind of
613 reference. :guilabel:`relation` is the table to look up that
620 A functional field is a field whose value is calculated by a function (rather
621 than being stored in the database).
625 fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type="float",
626 fnct_search=None, obj=None, method=False, store=False, multi=False
630 * :guilabel:`fnct` is the function or method that will compute the field
631 value. It must have been declared before declaring the functional field.
632 * :guilabel:`fnct_inv` is the function or method that will allow writing
633 values in that field.
634 * :guilabel:`type` is the field type name returned by the function. It can
635 be any field type name except function.
636 * :guilabel:`fnct_search` allows you to define the searching behaviour on
638 * :guilabel:`method` whether the field is computed by a method (of an
639 object) or a global function
640 * :guilabel:`store` If you want to store field in database or not. Default
642 * :guilabel:`multi` is a group name. All fields with the same `multi`
643 parameter will be calculated in a single function call.
647 If *method* is True, the signature of the method must be::
649 def fnct(self, cr, uid, ids, field_name, arg, context):
651 otherwise (if it is a global function), its signature must be::
653 def fnct(cr, table, ids, field_name, arg, context):
655 Either way, it must return a dictionary of values of the form
656 **{id'_1_': value'_1_', id'_2_': value'_2_',...}.**
658 The values of the returned dictionary must be of the type specified by the type
659 argument in the field declaration.
661 If *multi* is set, then *field_name* is replaced by *field_names*: a list
662 of the field names that should be calculated. Each value in the returned
663 dictionary is also a dictionary from field name to value. For example, if the
664 fields `'name'`, and `'age'` are both based on the `vital_statistics` function,
665 then the return value of `vital_statistics` might look like this when `ids` is
669 1: {'name': 'Bob', 'age': 23},
670 2: {'name': 'Sally', 'age', 19},
671 5: {'name': 'Ed', 'age': 62}
676 If *method* is true, the signature of the method must be::
678 def fnct(self, cr, uid, ids, field_name, field_value, arg, context):
681 otherwise (if it is a global function), it should be::
683 def fnct(cr, table, ids, field_name, field_value, arg, context):
685 fnct_search parameter
686 """""""""""""""""""""
687 If method is true, the signature of the method must be::
689 def fnct(self, cr, uid, obj, name, args, context):
691 otherwise (if it is a global function), it should be::
693 def fnct(cr, uid, obj, name, args, context):
695 The return value is a list containing 3-part tuples which are used in search function::
697 return [('id','in',[1,3,5])]
699 *obj* is the same as *self*, and *name* receives the field name. *args* is a list
700 of 3-part tuples containing search criteria for this field, although the search
701 function may be called separately for each tuple.
705 Suppose we create a contract object which is :
707 .. code-block:: python
709 class hr_contract(osv.osv):
710 _name = 'hr.contract'
711 _description = 'Contract'
713 'name' : fields.char('Contract Name', size=30, required=True),
714 'employee_id' : fields.many2one('hr.employee', 'Employee', required=True),
715 'function' : fields.many2one('res.partner.function', 'Function'),
719 If we want to add a field that retrieves the function of an employee by looking its current contract, we use a functional field. The object hr_employee is inherited this way:
721 .. code-block:: python
723 class hr_employee(osv.osv):
724 _name = "hr.employee"
725 _description = "Employee"
726 _inherit = "hr.employee"
728 'contract_ids' : fields.one2many('hr.contract', 'employee_id', 'Contracts'),
729 'function' : fields.function(
730 _get_cur_function_id,
732 obj="res.partner.function",
734 string='Contract Function'),
738 .. note:: three points
740 * :guilabel:`type` ='many2one' is because the function field must create
741 a many2one field; function is declared as a many2one in hr_contract also.
742 * :guilabel:`obj` ="res.partner.function" is used to specify that the
743 object to use for the many2one field is res.partner.function.
744 * We called our method :guilabel:`_get_cur_function_id` because its role
745 is to return a dictionary whose keys are ids of employees, and whose
746 corresponding values are ids of the function of those employees. The
747 code of this method is:
749 .. code-block:: python
751 def _get_cur_function_id(self, cr, uid, ids, field_name, arg, context):
753 #get the id of the current function of the employee of identifier "i"
755 SELECT f.id AS func_id
757 LEFT JOIN res_partner_function f ON (f.id = c.function)
763 sql_res = cr.dictfetchone()
765 if sql_res: #The employee has one associated contract
766 res[i] = sql_res['func_id']
768 #res[i] must be set to False and not to None because of XML:RPC
769 # "cannot marshal None unless allow_none is enabled"
773 The id of the function is retrieved using a SQL query. Note that if the query
774 returns no result, the value of sql_res['func_id'] will be None. We force the
775 False value in this case value because XML:RPC (communication between the server
776 and the client) doesn't allow to transmit this value.
780 It will calculate the field and store the result in the table. The field will be
781 recalculated when certain fields are changed on other objects. It uses the
784 .. code-block:: python
789 ['field_name1', 'field_name2'],
793 It will call function function_name when any changes are written to fields in the
794 list ['field1','field2'] on object 'object_name'. The function should have the
795 following signature::
797 def function_name(self, cr, uid, ids, context=None):
799 Where `ids` will be the ids of records in the other object's table that have
800 changed values in the watched fields. The function should return a list of ids
801 of records in its own table that should have the field recalculated. That list
802 will be sent as a parameter for the main function of the field.
804 Here's an example from the membership module:
806 .. code-block:: python
812 string='Current membership state',
816 'account.invoice': (_get_invoice_partner, ['state'], 10),
817 'membership.membership_line': (_get_partner_id,['state'], 10),
819 lambda self, cr, uid, ids, c={}: ids,
827 .. describe:: Declaring a property
829 A property is a special field: fields.property.
831 .. code-block:: python
833 class res_partner(osv.osv):
834 _name = "res.partner"
835 _inherit = "res.partner"
837 'property_product_pricelist':
841 relation='product.pricelist',
842 string="Sale Pricelist",
845 group_name="Pricelists Properties"),
849 Then you have to create the default value in a .XML file for this property:
853 <record model="ir.property" id="property_product_pricelist">
854 <field name="name">property_product_pricelist</field>
855 <field name="fields_id" search="[('model','=','res.partner'),
856 ('name','=','property_product_pricelist')]"/>
857 <field name="value" eval="'product.pricelist,'+str(list0)"/>
864 if the default value points to a resource from another module, you can use the ref function like this:
866 <field name="value" eval="'product.pricelist,'+str(ref('module.data_id'))"/>
868 **Putting properties in forms**
870 To add properties in forms, just put the <properties/> tag in your form. This will automatically add all properties fields that are related to this object. The system will add properties depending on your rights. (some people will be able to change a specific property, others won't).
872 Properties are displayed by section, depending on the group_name attribute. (It is rendered in the client like a separator tag).
874 **How does this work ?**
876 The fields.property class inherits from fields.function and overrides the read and write method. The type of this field is many2one, so in the form a property is represented like a many2one function.
878 But the value of a property is stored in the ir.property class/table as a complete record. The stored value is a field of type reference (not many2one) because each property may point to a different object. If you edit properties values (from the administration menu), these are represented like a field of type reference.
880 When you read a property, the program gives you the property attached to the instance of object you are reading. If this object has no value, the system will give you the default property.
882 The definition of a property is stored in the ir.model.fields class like any other fields. In the definition of the property, you can add groups that are allowed to change to property.
884 **Using properties or normal fields**
886 When you want to add a new feature, you will have to choose to implement it as a property or as normal field. Use a normal field when you inherit from an object and want to extend this object. Use a property when the new feature is not related to the object but to an external concept.
889 Here are a few tips to help you choose between a normal field or a property:
891 Normal fields extend the object, adding more features or data.
893 A property is a concept that is attached to an object and have special features:
895 * Different value for the same property depending on the company
896 * Rights management per field
897 * It's a link between resources (many2one)
899 **Example 1: Account Receivable**
901 The default "Account Receivable" for a specific partner is implemented as a property because:
903 * This is a concept related to the account chart and not to the partner, so it is an account property that is visible on a partner form. Rights have to be managed on this fields for accountants, these are not the same rights that are applied to partner objects. So you have specific rights just for this field of the partner form: only accountants may change the account receivable of a partner.
905 * This is a multi-company field: the same partner may have different account receivable values depending on the company the user belongs to. In a multi-company system, there is one account chart per company. The account receivable of a partner depends on the company it placed the sale order.
907 * The default account receivable is the same for all partners and is configured from the general property menu (in administration).
910 One interesting thing is that properties avoid "spaghetti" code. The account module depends on the partner (base) module. But you can install the partner (base) module without the accounting module. If you add a field that points to an account in the partner object, both objects will depend on each other. It's much more difficult to maintain and code (for instance, try to remove a table when both tables are pointing to each others.)
912 **Example 2: Product Times**
914 The product expiry module implements all delays related to products: removal date, product usetime, ... This module is very useful for food industries.
916 This module inherits from the product.product object and adds new fields to it:
918 .. code-block:: python
920 class product_product(osv.osv):
922 _inherit = 'product.product'
923 _name = 'product.product'
926 'life_time': fields.integer('Product lifetime'),
927 'use_time': fields.integer('Product usetime'),
928 'removal_time': fields.integer('Product removal time'),
929 'alert_time': fields.integer('Product alert time'),
936 This module adds simple fields to the product.product object. We did not use properties because:
938 * We extend a product, the life_time field is a concept related to a product, not to another object.
939 * We do not need a right management per field, the different delays are managed by the same people that manage all products.
945 Keeping the context in ORM methods
946 ++++++++++++++++++++++++++++++++++
948 In OpenObject, the context holds very important data such as the language in
949 which a document must be written, whether function field needs updating or not,
952 When calling an ORM method, you will probably already have a context - for
953 example the framework will provide you with one as a parameter of almost
955 If you do have a context, it is very important that you always pass it through
956 to every single method you call.
958 This rule also applies to writing ORM methods. You should expect to receive a
959 context as parameter, and always pass it through to every other method you call..