3 Objects, Fields and Methods
4 ===========================
9 .. This chapter is dedicated to detailed objects definition:
14 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...
16 Please note that there is an object for every type of resource, and not an
17 object per resource. We have thus a res.partner object to manage all the
18 partners and not a *res.partner* object per partner. If we talk in "object
19 oriented" terms, we could also say that there is an object per level.
21 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.
23 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::
25 res_partner.send_email(... , [1, 5], ...)
27 We will see the exact syntax of object method calls further in this document.
29 In the following section, we will see how to define a new object. Then, we will check out the different methods of doing this.
33 * OpenERP "objects" are usually called classes in object oriented programming.
34 * A OpenERP "resource" is usually called an object in OO programming, instance of a class.
36 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 ...
38 Luckily, an OpenERP "resource" can be converted magically into a nice Python object using the "browse" class method (OpenERP object method).
41 The ORM - Object-relational mapping - Models
42 --------------------------------------------
44 The ORM, short for Object-Relational Mapping, is a central part of OpenERP.
46 In OpenERP, the data model is described and manipulated through Python classes
47 and objects. It is the ORM job to bridge the gap -- as transparently as
48 possible for the developer -- between Python and the underlying relational
49 database (PostgreSQL), which will provide the persistence we need for our
53 OpenERP Object Attributes
54 -------------------------
59 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.
64 The first line of the object definition will always be of the form::
66 class name_of_the_object(osv.osv):
67 _name = 'name.of.the.object'
72 An object is defined by declaring some fields with predefined names in the
73 class. Two of them are required (_name and _columns), the rest are optional.
74 The predefined fields are:
80 Determines whether a corresponding PostgreSQL table must be generated
81 automatically from the object. Setting _auto to False can be useful in case
82 of OpenERP objects generated from PostgreSQL views. See the "Reporting From
83 PostgreSQL Views" section for more details.
86 The object fields. See the :ref:`fields <fields-link>` section for further details.
89 The constraints on the object. See the constraints section for details.
92 The SQL Constraint on the object. See the SQL constraints section for further details.
95 The default values for some of the object's fields. See the default value section for details.
98 The name of the osv object which the current object inherits from. See the :ref:`object inheritance section<inherit-link>`
99 (first form) for further details.
102 The list of osv objects the object inherits from. This list must be given in
103 a python dictionary of the form: {'name_of_the_parent_object':
104 'name_of_the_field', ...}. See the :ref:`object inheritance section<inherits-link>`
105 (second form) for further details. Default value: {}.
108 Determines whether or not the write access to the resource must be logged.
109 If true, four fields will be created in the SQL table: create_uid,
110 create_date, write_uid, write_date. Those fields represent respectively the
111 id of the user who created the record, the creation date of record, the id
112 of the user who last modified the record, and the date of that last
113 modification. This data may be obtained by using the perm_read method.
116 Name of the object. Default value: None.
119 Name of the fields used to sort the results of the search and read methods.
126 _order = "date_order desc"
129 Name of the field in which the name of every resource is stored. Default
130 value: 'name'. Note: by default, the name_get method simply returns the
131 content of this field.
134 Name of the SQL sequence that manages the ids for this object. Default value: None.
137 SQL code executed upon creation of the object (only if _auto is True). It means this code gets executed after the table is created.
140 Name of the SQL table. Default value: the value of the _name field above
141 with the dots ( . ) replaced by underscores ( _ ).
146 Object Inheritance - _inherit
147 -----------------------------
152 Objects may be inherited in some custom or specific modules. It is better to
153 inherit an object to add/modify some fields.
157 _inherit='object.name'
159 Extension of an object
160 ++++++++++++++++++++++
162 There are two possible ways to do this kind of inheritance. Both ways result in
163 a new class of data, which holds parent fields and behaviour as well as
164 additional fields and behaviour, but they differ in heavy programatical
167 While Example 1 creates a new subclass "custom_material" that may be "seen" or
168 "used" by any view or tree which handles "network.material", this will not be
169 the case for Example 2.
171 This is due to the table (other.material) the new subclass is operating on,
172 which will never be recognized by previous "network.material" views or trees.
176 class custom_material(osv.osv):
177 _name = 'network.material'
178 _inherit = 'network.material'
180 'manuf_warranty': fields.boolean('Manufacturer warranty?'),
183 'manuf_warranty': lambda *a: False,
191 In this example, the 'custom_material' will add a new field 'manuf_warranty' to
192 the object 'network.material'. New instances of this class will be visible by
193 views or trees operating on the superclasses table 'network.material'.
195 This inheritancy is usually called "class inheritance" in Object oriented
196 design. The child inherits data (fields) and behavior (functions) of his
202 class other_material(osv.osv):
203 _name = 'other.material'
204 _inherit = 'network.material'
206 'manuf_warranty': fields.boolean('Manufacturer warranty?'),
209 'manuf_warranty': lambda *a: False,
217 In this example, the 'other_material' will hold all fields specified by
218 'network.material' and it will additionally hold a new field 'manuf_warranty'.
219 All those fields will be part of the table 'other.material'. New instances of
220 this class will therefore never been seen by views or trees operating on the
221 superclasses table 'network.material'.
223 This type of inheritancy is known as "inheritance by prototyping" (e.g.
224 Javascript), because the newly created subclass "copies" all fields from the
225 specified superclass (prototype). The child inherits data (fields) and behavior
226 (functions) of his parent.
231 Inheritance by Delegation - _inherits
232 -------------------------------------
236 class tiny_object(osv.osv)
237 _name = 'tiny.object'
238 _table = 'tiny_object'
240 'tiny.object_a': 'object_a_id',
241 'tiny.object_b': 'object_b_id',
243 'tiny.object_n': 'object_n_id'
247 The object 'tiny.object' inherits from all the columns and all the methods from
248 the n objects 'tiny.object_a', ..., 'tiny.object_n'.
250 To inherit from multiple tables, the technique consists in adding one column to
251 the table tiny_object per inherited object. This column will store a foreign
252 key (an id from another table). The values *'object_a_id' 'object_b_id' ...
253 'object_n_id'* are of type string and determine the title of the columns in
254 which the foreign keys from 'tiny.object_a', ..., 'tiny.object_n' are stored.
256 This inheritance mechanism is usually called " *instance inheritance* " or "
257 *value inheritance* ". A resource (instance) has the VALUES of its parents.
265 Objects may contain different types of fields. Those types can be divided into
266 three categories: simple types, relation types and functional fields. The
267 simple types are integers, floats, booleans, strings, etc ... ; the relation
268 types are used to represent relations between objects (one2one, one2many,
269 many2one). Functional fields are special fields because they are not stored in
270 the database but calculated in real time given other fields of the view.
272 Here's the header of the initialization method of the class any field defined
273 in OpenERP inherits (as you can see in server/bin/osv/fields.py)::
275 def __init__(self, string='unknown', required=False, readonly=False,
276 domain=None, context="", states=None, priority=0, change_default=False, size=None,
277 ondelete="set null", translate=False, select=False, **args) :
279 There are a common set of optional parameters that are available to most field
283 Whether or not the user can define default values on other fields depending
284 on the value of this field. Those default values need to be defined in
287 A description of how the field should be used: longer and more descriptive
288 than `string`. It will appear in a tooltip when the mouse hovers over the
291 How to handle deletions in a related record. Allowable values are:
292 'restrict', 'no action', 'cascade', 'set null', and 'set default'.
294 :readonly: `True` if the user cannot edit this field, otherwise `False`.
296 `True` if this field must have a value before the object can be saved,
298 :size: The size of the field in the database: number characters or digits.
300 Lets you override other parameters for specific states of this object.
301 Accepts a dictionary with the state names as keys and a list of name/value
302 tuples as the values. For example: `states={'posted':[('readonly',True)]}`
304 The field name as it should appear in a label or column header. Strings
305 containing non-ASCII characters must use python unicode objects.
306 For example: `'tested': fields.boolean(u'Testé')`
308 `True` if the *content* of this field should be translated, otherwise
311 There are also some optional parameters that are specific to some field types:
314 Define a variable's value visible in the view's context or an on-change
315 function. Used when searching child table of `one2many` relationship?
317 Domain restriction on a relational field.
321 Example: domain=[('field','=',value)])
322 :invisible: Hide the field's value in forms. For example, a password.
324 Default value for the `on_change` attribute in the view. This will launch
325 a function on the server when the field changes in the client. For example,
326 `on_change="onchange_shop_id(shop_id)"`.
328 Used when a field is an id reference to another table. This is the name of
329 the table to look in. Most commonly used with related and function field
332 Default value for the `select` attribute in the view. 1 means basic search,
333 and 2 means advanced search.
344 A boolean (true, false).
348 fields.boolean('Field Name' [, Optional Parameters]),
356 fields.integer('Field Name' [, Optional Parameters]),
360 A floating point number.
364 fields.float('Field Name' [, Optional Parameters]),
368 The optional parameter digits defines the precision and scale of the
369 number. The scale being the number of digits after the decimal point
370 whereas the precision is the total number of significant digits in the
371 number (before and after the decimal point). If the parameter digits is
372 not present, the number will be a double precision floating point number.
373 Warning: these floating-point numbers are inexact (not any value can be
374 converted to its binary representation) and this can lead to rounding
375 errors. You should always use the digits parameter for monetary amounts.
379 'rate': fields.float(
380 'Relative Change rate',
382 Optional Parameters]),
386 A string of limited length. The required size parameter determines its size.
393 Optional Parameters]), # where ''n'' is an integer.
397 'city' : fields.char('City Name', size=30, required=True),
401 A text field with no limit in length.
405 fields.text('Field Name' [, Optional Parameters]),
413 fields.date('Field Name' [, Optional Parameters]),
417 Allows to store a date and the time of day in the same field.
421 fields.datetime('Field Name' [, Optional Parameters]),
429 A field which allows the user to make a selection between various predefined values.
433 fields.selection((('n','Unconfirmed'), ('c','Confirmed')),
434 'Field Name' [, Optional Parameters]),
438 Format of the selection parameter: tuple of tuples of strings of the form::
440 (('key_or_value', 'string_to_display'), ... )
443 You can specify a function that will return the tuple. Example ::
445 def _get_selection(self, cursor, user_id, context=None):
447 ('choice1', 'This is the choice 1'),
448 ('choice2', 'This is the choice 2'))
451 'sel' : fields.selection(
453 'What do you want ?')
458 Using relation fields **many2one** with **selection**. In fields definitions add::
461 'my_field': fields.many2one(
462 'mymodule.relation.model',
464 selection=_sel_func),
467 And then define the _sel_func like this (but before the fields definitions)::
469 def _sel_func(self, cr, uid, context=None):
470 obj = self.pool.get('mymodule.relation.model')
471 ids = obj.search(cr, uid, [])
472 res = obj.read(cr, uid, ids, ['name', 'id'], context)
473 res = [(r['id'], r['name']) for r in res]
481 A one2one field expresses a one:to:one relation between two objects. It is
482 deprecated. Use many2one instead.
486 fields.one2one('other.object.name', 'Field Name')
490 Associates this object to a parent object via this Field. For example
491 Department an Employee belongs to would Many to one. i.e Many employees will
492 belong to a Department
503 - ondelete: What should happen when the resource this field points to is deleted.
504 + Predefined value: "cascade", "set null", "restrict", "no action", "set default"
505 + Default value: "set null"
508 - select: True - (creates an index on the Foreign Key field)
512 'commercial': fields.many2one(
530 - invisible: True/False
532 - readonly: True/False
536 'address': fields.one2many(
537 'res.partner.address',
547 fields.many2many('other.object.name',
554 - other.object.name is the other object which belongs to the relation
555 - relation object is the table that makes the link
556 - actual.object.id and other.object.id are the fields' names used in the relation table
562 'res.partner.category',
563 'res_partner_category_rel',
568 To make it bidirectional (= create a field in the other object)::
570 class other_object_name2(osv.osv):
571 _inherit = 'other.object.name'
573 'other_fields': fields.many2many(
574 'actual.object.name',
584 class res_partner_category2(osv.osv):
585 _inherit = 'res.partner.category'
587 'partner_ids': fields.many2many(
589 'res_partner_category_rel',
594 res_partner_category2()
598 Sometimes you need to refer to the relation of a relation. For example,
599 supposing you have objects: City -> State -> Country, and you need to refer to
600 the Country from a City, you can define a field as below in the City object::
602 'country_id': fields.related(
606 relation="res.country",
611 - The first set of parameters are the chain of reference fields to
612 follow, with the desired field at the end.
613 - :guilabel:`type` is the type of that desired field.
614 - Use :guilabel:`relation` if the desired field is still some kind of
615 reference. :guilabel:`relation` is the table to look up that
622 A functional field is a field whose value is calculated by a function (rather
623 than being stored in the database).
627 fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type="float",
628 fnct_search=None, obj=None, method=False, store=False, multi=False
632 * :guilabel:`fnct` is the function or method that will compute the field
633 value. It must have been declared before declaring the functional field.
634 * :guilabel:`fnct_inv` is the function or method that will allow writing
635 values in that field.
636 * :guilabel:`type` is the field type name returned by the function. It can
637 be any field type name except function.
638 * :guilabel:`fnct_search` allows you to define the searching behaviour on
640 * :guilabel:`method` whether the field is computed by a method (of an
641 object) or a global function
642 * :guilabel:`store` If you want to store field in database or not. Default
644 * :guilabel:`multi` is a group name. All fields with the same `multi`
645 parameter will be calculated in a single function call.
649 If *method* is True, the signature of the method must be::
651 def fnct(self, cr, uid, ids, field_name, arg, context):
653 otherwise (if it is a global function), its signature must be::
655 def fnct(cr, table, ids, field_name, arg, context):
657 Either way, it must return a dictionary of values of the form
658 **{id'_1_': value'_1_', id'_2_': value'_2_',...}.**
660 The values of the returned dictionary must be of the type specified by the type
661 argument in the field declaration.
663 If *multi* is set, then *field_name* is replaced by *field_names*: a list
664 of the field names that should be calculated. Each value in the returned
665 dictionary is also a dictionary from field name to value. For example, if the
666 fields `'name'`, and `'age'` are both based on the `vital_statistics` function,
667 then the return value of `vital_statistics` might look like this when `ids` is
671 1: {'name': 'Bob', 'age': 23},
672 2: {'name': 'Sally', 'age', 19},
673 5: {'name': 'Ed', 'age': 62}
678 If *method* is true, the signature of the method must be::
680 def fnct(self, cr, uid, ids, field_name, field_value, arg, context):
683 otherwise (if it is a global function), it should be::
685 def fnct(cr, table, ids, field_name, field_value, arg, context):
687 fnct_search parameter
688 """""""""""""""""""""
689 If method is true, the signature of the method must be::
691 def fnct(self, cr, uid, obj, name, args, context):
693 otherwise (if it is a global function), it should be::
695 def fnct(cr, uid, obj, name, args, context):
697 The return value is a list containing 3-part tuples which are used in search function::
699 return [('id','in',[1,3,5])]
701 *obj* is the same as *self*, and *name* receives the field name. *args* is a list
702 of 3-part tuples containing search criteria for this field, although the search
703 function may be called separately for each tuple.
707 Suppose we create a contract object which is :
709 .. code-block:: python
711 class hr_contract(osv.osv):
712 _name = 'hr.contract'
713 _description = 'Contract'
715 'name' : fields.char('Contract Name', size=30, required=True),
716 'employee_id' : fields.many2one('hr.employee', 'Employee', required=True),
717 'function' : fields.many2one('res.partner.function', 'Function'),
721 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:
723 .. code-block:: python
725 class hr_employee(osv.osv):
726 _name = "hr.employee"
727 _description = "Employee"
728 _inherit = "hr.employee"
730 'contract_ids' : fields.one2many('hr.contract', 'employee_id', 'Contracts'),
731 'function' : fields.function(
732 _get_cur_function_id,
734 obj="res.partner.function",
736 string='Contract Function'),
740 .. note:: three points
742 * :guilabel:`type` ='many2one' is because the function field must create
743 a many2one field; function is declared as a many2one in hr_contract also.
744 * :guilabel:`obj` ="res.partner.function" is used to specify that the
745 object to use for the many2one field is res.partner.function.
746 * We called our method :guilabel:`_get_cur_function_id` because its role
747 is to return a dictionary whose keys are ids of employees, and whose
748 corresponding values are ids of the function of those employees. The
749 code of this method is:
751 .. code-block:: python
753 def _get_cur_function_id(self, cr, uid, ids, field_name, arg, context):
755 #get the id of the current function of the employee of identifier "i"
757 SELECT f.id AS func_id
759 LEFT JOIN res_partner_function f ON (f.id = c.function)
765 sql_res = cr.dictfetchone()
767 if sql_res: #The employee has one associated contract
768 res[i] = sql_res['func_id']
770 #res[i] must be set to False and not to None because of XML:RPC
771 # "cannot marshal None unless allow_none is enabled"
775 The id of the function is retrieved using a SQL query. Note that if the query
776 returns no result, the value of sql_res['func_id'] will be None. We force the
777 False value in this case value because XML:RPC (communication between the server
778 and the client) doesn't allow to transmit this value.
782 It will calculate the field and store the result in the table. The field will be
783 recalculated when certain fields are changed on other objects. It uses the
786 .. code-block:: python
791 ['field_name1', 'field_name2'],
795 It will call function function_name when any changes are written to fields in the
796 list ['field1','field2'] on object 'object_name'. The function should have the
797 following signature::
799 def function_name(self, cr, uid, ids, context=None):
801 Where `ids` will be the ids of records in the other object's table that have
802 changed values in the watched fields. The function should return a list of ids
803 of records in its own table that should have the field recalculated. That list
804 will be sent as a parameter for the main function of the field.
806 Here's an example from the membership module:
808 .. code-block:: python
814 string='Current membership state',
818 'account.invoice': (_get_invoice_partner, ['state'], 10),
819 'membership.membership_line': (_get_partner_id,['state'], 10),
821 lambda self, cr, uid, ids, c={}: ids,
829 .. describe:: Declaring a property
831 A property is a special field: fields.property.
833 .. code-block:: python
835 class res_partner(osv.osv):
836 _name = "res.partner"
837 _inherit = "res.partner"
839 'property_product_pricelist':
843 relation='product.pricelist',
844 string="Sale Pricelist",
846 group_name="Pricelists Properties"),
850 Then you have to create the default value in a .XML file for this property:
854 <record model="ir.property" id="property_product_pricelist">
855 <field name="name">property_product_pricelist</field>
856 <field name="fields_id" search="[('model','=','res.partner'),
857 ('name','=','property_product_pricelist')]"/>
858 <field name="value" eval="'product.pricelist,'+str(list0)"/>
865 if the default value points to a resource from another module, you can use the ref function like this:
867 <field name="value" eval="'product.pricelist,'+str(ref('module.data_id'))"/>
869 **Putting properties in forms**
871 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).
873 Properties are displayed by section, depending on the group_name attribute. (It is rendered in the client like a separator tag).
875 **How does this work ?**
877 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.
879 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.
881 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.
883 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.
885 **Using properties or normal fields**
887 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.
890 Here are a few tips to help you choose between a normal field or a property:
892 Normal fields extend the object, adding more features or data.
894 A property is a concept that is attached to an object and have special features:
896 * Different value for the same property depending on the company
897 * Rights management per field
898 * It's a link between resources (many2one)
900 **Example 1: Account Receivable**
902 The default "Account Receivable" for a specific partner is implemented as a property because:
904 * 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.
906 * 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.
908 * The default account receivable is the same for all partners and is configured from the general property menu (in administration).
911 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.)
913 **Example 2: Product Times**
915 The product expiry module implements all delays related to products: removal date, product usetime, ... This module is very useful for food industries.
917 This module inherits from the product.product object and adds new fields to it:
919 .. code-block:: python
921 class product_product(osv.osv):
923 _inherit = 'product.product'
924 _name = 'product.product'
927 'life_time': fields.integer('Product lifetime'),
928 'use_time': fields.integer('Product usetime'),
929 'removal_time': fields.integer('Product removal time'),
930 'alert_time': fields.integer('Product alert time'),
937 This module adds simple fields to the product.product object. We did not use properties because:
939 * We extend a product, the life_time field is a concept related to a product, not to another object.
940 * We do not need a right management per field, the different delays are managed by the same people that manage all products.
946 Keeping the context in ORM methods
947 ++++++++++++++++++++++++++++++++++
949 In OpenObject, the context holds very important data such as the language in
950 which a document must be written, whether function field needs updating or not,
953 When calling an ORM method, you will probably already have a context - for
954 example the framework will provide you with one as a parameter of almost
956 If you do have a context, it is very important that you always pass it through
957 to every single method you call.
959 This rule also applies to writing ORM methods. You should expect to receive a
960 context as parameter, and always pass it through to every other method you call..