second submodule: website_house_booking
[odoo/odoo.git] / doc / 03_module_dev_02.rst
1 .. _module-dev-api:
2
3 Objects, Fields and Methods
4 ===========================
5
6 OpenERP Objects
7 ---------------
8
9 .. This chapter is dedicated to detailed objects definition:
10     all fields
11     all objects
12     inheritancies
13
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...
15
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.
20
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.
22
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::
24
25         res_partner.send_email(... , [1, 5], ...)
26
27 We will see the exact syntax of object method calls further in this document.
28
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.
30
31 For developers:
32
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. 
35
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 ...
37
38 Luckily, an OpenERP "resource" can be converted magically into a nice Python object using the "browse" class method (OpenERP object method).
39
40
41 The ORM - Object-relational mapping - Models
42 --------------------------------------------
43
44 The ORM, short for Object-Relational Mapping, is a central part of OpenERP.
45
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
50 objects.
51
52
53 OpenERP Object Attributes
54 -------------------------
55
56 Objects Introduction
57 ++++++++++++++++++++
58
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.
60
61 Object definition
62 +++++++++++++++++
63
64 The first line of the object definition will always be of the form::
65
66         class name_of_the_object(osv.osv):
67                 _name = 'name.of.the.object'
68                 _columns = { ... }
69                 ...
70         name_of_the_object()
71
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:
75
76 Predefined fields
77 +++++++++++++++++
78
79 `_auto`
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.
84
85 `_columns (required)`
86   The object fields. See the :ref:`fields <fields-link>` section for further details.
87
88 `_constraints`
89   The constraints on the object. See the constraints section for details.
90
91 `_sql_constraints`
92   The SQL Constraint on the object. See the SQL constraints section for further details.
93
94 `_defaults`
95   The default values for some of the object's fields. See the default value section for details.
96
97 `_inherit`
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.
100
101 `_inherits`
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: {}.
106
107 `_log_access`
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.
114
115 `_name (required)`
116   Name of the object. Default value: None.
117
118 `_order`
119   Name of the fields used to sort the results of the search and read methods.
120
121   Default value: 'id'.
122
123   Examples::
124
125     _order = "name"  
126     _order = "date_order desc"
127
128 `_rec_name`
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.
132
133 `_sequence`
134   Name of the SQL sequence that manages the ids for this object. Default value: None.
135
136 `_sql`
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.
138
139 `_table`
140   Name of the SQL table. Default value: the value of the _name field above
141   with the dots ( . ) replaced by underscores ( _ ). 
142
143
144 .. _inherit-link:
145
146 Object Inheritance - _inherit
147 -----------------------------
148
149 Introduction
150 ++++++++++++
151
152 Objects may be inherited in some custom or specific modules. It is better to
153 inherit an object to add/modify some fields.
154
155 It is done with::
156
157     _inherit='object.name'
158
159 Extension of an object
160 ++++++++++++++++++++++
161
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
165 consequences.
166
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.
170
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.
173
174 Example 1::
175
176     class custom_material(osv.osv):
177         _name = 'network.material'
178         _inherit = 'network.material'
179         _columns = {
180             'manuf_warranty': fields.boolean('Manufacturer warranty?'),
181         }
182         _defaults = {
183             'manuf_warranty': lambda *a: False,
184         }
185         custom_material()
186
187 .. tip:: Notice
188
189     _name == _inherit
190
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'.
194
195 This inheritancy is usually called "class inheritance" in Object oriented
196 design. The child inherits data (fields) and behavior (functions) of his
197 parent.
198
199
200 Example 2::
201
202     class other_material(osv.osv):
203         _name = 'other.material'
204         _inherit = 'network.material'
205         _columns = {
206             'manuf_warranty': fields.boolean('Manufacturer warranty?'),
207         }
208         _defaults = {
209             'manuf_warranty': lambda *a: False,
210         }
211         other_material()
212
213 .. tip:: Notice
214
215     _name != _inherit
216
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'.
222
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.
227
228
229 .. _inherits-link:
230
231 Inheritance by Delegation - _inherits
232 -------------------------------------
233
234  **Syntax :**::
235
236     class tiny_object(osv.osv)
237         _name = 'tiny.object'
238         _table = 'tiny_object'
239         _inherits = {
240             'tiny.object_a': 'object_a_id',
241             'tiny.object_b': 'object_b_id',
242             ... ,
243             'tiny.object_n': 'object_n_id'
244         }
245         (...)
246
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'.
249
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.
255
256 This inheritance mechanism is usually called " *instance inheritance* "  or  "
257 *value inheritance* ". A resource (instance) has the VALUES of its parents.
258
259
260 .. _fields-link:
261
262 Fields Introduction
263 -------------------
264
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.
271
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)::
274
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) :
278
279 There are a common set of optional parameters that are available to most field
280 types:
281
282 :change_default: 
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
285         the ir.values table.
286 :help: 
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 
289         field.
290 :ondelete: 
291         How to handle deletions in a related record. Allowable values are: 
292         'restrict', 'no action', 'cascade', 'set null', and 'set default'.
293 :priority: Not used?
294 :readonly: `True` if the user cannot edit this field, otherwise `False`.
295 :required:
296         `True` if this field must have a value before the object can be saved, 
297         otherwise `False`.
298 :size: The size of the field in the database: number characters or digits.
299 :states:
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)]}`
303 :string: 
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é')` 
307 :translate:
308         `True` if the *content* of this field should be translated, otherwise 
309         `False`.
310
311 There are also some optional parameters that are specific to some field types:
312
313 :context: 
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?
316 :domain: 
317     Domain restriction on a relational field.
318
319     Default value: []. 
320
321     Example: domain=[('field','=',value)])
322 :invisible: Hide the field's value in forms. For example, a password.
323 :on_change:
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)"`. 
327 :relation:
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
330         types.
331 :select: 
332         Default value for the `select` attribute in the view. 1 means basic search,
333         and 2 means advanced search.
334
335
336 Type of Fields
337 --------------
338
339 Basic Types
340 +++++++++++
341
342 :boolean:
343
344         A boolean (true, false).
345
346         Syntax::
347
348                 fields.boolean('Field Name' [, Optional Parameters]),
349
350 :integer:
351
352         An integer.
353
354         Syntax::
355
356                 fields.integer('Field Name' [, Optional Parameters]),
357
358 :float:
359
360     A floating point number.
361
362     Syntax::
363
364                 fields.float('Field Name' [, Optional Parameters]),
365
366     .. note::
367
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.
376
377     Example::
378
379         'rate': fields.float(
380             'Relative Change rate',
381             digits=(12,6) [,
382             Optional Parameters]),
383
384 :char:
385
386   A string of limited length. The required size parameter determines its size.
387
388   Syntax::
389
390         fields.char(
391                 'Field Name', 
392                 size=n [, 
393                 Optional Parameters]), # where ''n'' is an integer.
394
395   Example::
396
397         'city' : fields.char('City Name', size=30, required=True),
398
399 :text:
400
401   A text field with no limit in length.
402
403   Syntax::
404
405                 fields.text('Field Name' [, Optional Parameters]),
406
407 :date:
408
409   A date.
410
411   Syntax::
412
413                 fields.date('Field Name' [, Optional Parameters]),
414
415 :datetime:
416
417   Allows to store a date and the time of day in the same field.
418
419   Syntax::
420
421                 fields.datetime('Field Name' [, Optional Parameters]),
422
423 :binary:
424
425   A binary chain
426
427 :selection:
428
429   A field which allows the user to make a selection between various predefined values.
430
431   Syntax::
432
433                 fields.selection((('n','Unconfirmed'), ('c','Confirmed')),
434                                    'Field Name' [, Optional Parameters]),
435
436   .. note::
437
438              Format of the selection parameter: tuple of tuples of strings of the form::
439
440                 (('key_or_value', 'string_to_display'), ... )
441                 
442   .. note::
443              You can specify a function that will return the tuple. Example ::
444              
445                  def _get_selection(self, cursor, user_id, context=None):
446                      return (
447                         ('choice1', 'This is the choice 1'), 
448                         ('choice2', 'This is the choice 2'))
449                      
450                  _columns = {
451                     'sel' : fields.selection(
452                         _get_selection, 
453                         'What do you want ?')
454                  }
455
456   *Example*
457
458   Using relation fields **many2one** with **selection**. In fields definitions add::
459
460         ...,
461         'my_field': fields.many2one(
462                 'mymodule.relation.model', 
463                 'Title', 
464                 selection=_sel_func),
465         ...,
466
467   And then define the _sel_func like this (but before the fields definitions)::
468
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]
474             return res
475
476 Relational Types
477 ++++++++++++++++
478
479 :one2one:
480
481   A one2one field expresses a one:to:one relation between two objects. It is
482   deprecated. Use many2one instead.
483
484   Syntax::
485
486                 fields.one2one('other.object.name', 'Field Name')
487
488 :many2one:
489
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
493
494   Syntax::
495
496                 fields.many2one(
497                         'other.object.name', 
498                         'Field Name', 
499                         optional parameters)
500
501   Optional parameters:
502   
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"
506     - required: True
507     - readonly: True
508     - select: True - (creates an index on the Foreign Key field)
509
510   *Example* ::
511
512                 'commercial': fields.many2one(
513                         'res.users', 
514                         'Commercial', 
515                         ondelete='cascade'),
516
517 :one2many:
518
519   TODO
520
521   Syntax::
522
523                 fields.one2many(
524                         'other.object.name', 
525                         'Field relation id', 
526                         'Fieldname', 
527                         optional parameter)
528
529   Optional parameters:
530                 - invisible: True/False
531                 - states: ?
532                 - readonly: True/False
533
534   *Example* ::
535
536                 'address': fields.one2many(
537                         'res.partner.address', 
538                         'partner_id', 
539                         'Contacts'),
540
541 :many2many:
542
543         TODO
544
545         Syntax::
546
547                 fields.many2many('other.object.name',
548                                  'relation object',
549                                  'actual.object.id',
550                                  'other.object.id',                                 
551                                  'Field Name')
552
553         Where:
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
557
558         Example::
559
560                 'category_ids':
561                    fields.many2many(
562                     'res.partner.category',
563                     'res_partner_category_rel',
564                     'partner_id',
565                     'category_id',
566                     'Categories'),
567
568         To make it bidirectional (= create a field in the other object)::
569
570                 class other_object_name2(osv.osv):
571                     _inherit = 'other.object.name'
572                     _columns = {
573                         'other_fields': fields.many2many(
574                             'actual.object.name', 
575                             'relation object', 
576                             'actual.object.id', 
577                             'other.object.id', 
578                             'Other Field Name'),
579                     }
580                 other_object_name2()
581
582         Example::
583
584                 class res_partner_category2(osv.osv):
585                     _inherit = 'res.partner.category'
586                     _columns = {
587                         'partner_ids': fields.many2many(
588                             'res.partner', 
589                             'res_partner_category_rel', 
590                             'category_id', 
591                             'partner_id', 
592                             'Partners'),
593                     }
594                 res_partner_category2()
595
596 :related:
597
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::
601
602         'country_id': fields.related(
603             'state_id', 
604             'country_id', 
605             type="many2one",
606             relation="res.country",
607             string="Country", 
608             store=False)
609
610   Where:
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
616           reference in.
617
618 .. _fields-functional:
619
620 Functional Fields
621 +++++++++++++++++
622
623 A functional field is a field whose value is calculated by a function (rather
624 than being stored in the database).
625
626 **Parameters:** ::
627
628     fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type="float",
629         fnct_search=None, obj=None, method=False, store=False, multi=False
630
631 where
632
633     * :guilabel:`fnct` is the function or method that will compute the field 
634       value. It must have been declared before declaring the functional field.
635     * :guilabel:`fnct_inv` is the function or method that will allow writing
636       values in that field.
637     * :guilabel:`type` is the field type name returned by the function. It can
638       be any field type name except function.
639     * :guilabel:`fnct_search` allows you to define the searching behaviour on
640       that field.
641     * :guilabel:`method` whether the field is computed by a method (of an
642       object) or a global function
643     * :guilabel:`store` If you want to store field in database or not. Default
644       is False.
645     * :guilabel:`multi` is a group name. All fields with the same `multi`
646       parameter will be calculated in a single function call. 
647
648 fnct parameter
649 """"""""""""""
650 If *method* is True, the signature of the method must be::
651
652     def fnct(self, cr, uid, ids, field_name, arg, context):
653
654 otherwise (if it is a global function), its signature must be::
655
656     def fnct(cr, table, ids, field_name, arg, context):
657
658 Either way, it must return a dictionary of values of the form
659 **{id'_1_': value'_1_', id'_2_': value'_2_',...}.**
660
661 The values of the returned dictionary must be of the type specified by the type 
662 argument in the field declaration.
663
664 If *multi* is set, then *field_name* is replaced by *field_names*: a list
665 of the field names that should be calculated. Each value in the returned 
666 dictionary is also a dictionary from field name to value. For example, if the
667 fields `'name'`, and `'age'` are both based on the `vital_statistics` function,
668 then the return value of `vital_statistics` might look like this when `ids` is
669 `[1, 2, 5]`::
670
671     {
672         1: {'name': 'Bob', 'age': 23}, 
673         2: {'name': 'Sally', 'age', 19}, 
674         5: {'name': 'Ed', 'age': 62}
675     }
676
677 fnct_inv parameter
678 """"""""""""""""""
679 If *method* is true, the signature of the method must be::
680
681     def fnct(self, cr, uid, ids, field_name, field_value, arg, context):
682     
683
684 otherwise (if it is a global function), it should be::
685
686     def fnct(cr, table, ids, field_name, field_value, arg, context):
687
688 fnct_search parameter
689 """""""""""""""""""""
690 If method is true, the signature of the method must be::
691
692     def fnct(self, cr, uid, obj, name, args, context):
693
694 otherwise (if it is a global function), it should be::
695
696     def fnct(cr, uid, obj, name, args, context):
697
698 The return value is a list containing 3-part tuples which are used in search function::
699
700     return [('id','in',[1,3,5])]
701
702 *obj* is the same as *self*, and *name* receives the field name. *args* is a list
703 of 3-part tuples containing search criteria for this field, although the search
704 function may be called separately for each tuple.
705
706 Example
707 """""""
708 Suppose we create a contract object which is :
709
710 .. code-block:: python
711
712     class hr_contract(osv.osv):
713         _name = 'hr.contract'
714         _description = 'Contract'
715         _columns = {
716             'name' : fields.char('Contract Name', size=30, required=True),
717             'employee_id' : fields.many2one('hr.employee', 'Employee', required=True),
718             'function' : fields.many2one('res.partner.function', 'Function'),
719         }
720     hr_contract()
721
722 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
724 .. code-block:: python
725
726     class hr_employee(osv.osv):
727         _name = "hr.employee"
728         _description = "Employee"
729         _inherit = "hr.employee"
730         _columns = {
731             'contract_ids' : fields.one2many('hr.contract', 'employee_id', 'Contracts'),
732             'function' : fields.function(
733                 _get_cur_function_id, 
734                 type='many2one', 
735                 obj="res.partner.function",
736                 method=True, 
737                 string='Contract Function'),
738         }
739     hr_employee()
740
741 .. note:: three points
742
743         * :guilabel:`type` ='many2one' is because the function field must create
744           a many2one field; function is declared as a many2one in hr_contract also.
745         * :guilabel:`obj` ="res.partner.function" is used to specify that the
746           object to use for the many2one field is res.partner.function.
747         * We called our method :guilabel:`_get_cur_function_id` because its role
748           is to return a dictionary whose keys are ids of employees, and whose
749           corresponding values are ids of the function of those employees. The 
750           code of this method is:
751
752 .. code-block:: python
753
754     def _get_cur_function_id(self, cr, uid, ids, field_name, arg, context):
755         for i in ids:
756             #get the id of the current function of the employee of identifier "i"
757             sql_req= """
758             SELECT f.id AS func_id
759             FROM hr_contract c
760               LEFT JOIN res_partner_function f ON (f.id = c.function)
761             WHERE
762               (c.employee_id = %d)
763             """ % (i,)
764     
765             cr.execute(sql_req)
766             sql_res = cr.dictfetchone()
767     
768             if sql_res: #The employee has one associated contract
769                 res[i] = sql_res['func_id']
770             else:
771                 #res[i] must be set to False and not to None because of XML:RPC
772                 # "cannot marshal None unless allow_none is enabled"
773                 res[i] = False
774         return res
775
776 The id of the function is retrieved using a SQL query. Note that if the query 
777 returns no result, the value of sql_res['func_id'] will be None. We force the
778 False value in this case value because XML:RPC (communication between the server 
779 and the client) doesn't allow to transmit this value.
780
781 store Parameter
782 """""""""""""""
783 It will calculate the field and store the result in the table. The field will be
784 recalculated when certain fields are changed on other objects. It uses the
785 following syntax:
786
787 .. code-block:: python
788
789     store = {
790         'object_name': (
791                 function_name, 
792                 ['field_name1', 'field_name2'],
793                 priority)
794     }
795
796 It will call function function_name when any changes are written to fields in the
797 list ['field1','field2'] on object 'object_name'. The function should have the
798 following signature::
799
800     def function_name(self, cr, uid, ids, context=None):
801
802 Where `ids` will be the ids of records in the other object's table that have
803 changed values in the watched fields. The function should return a list of ids
804 of records in its own table that should have the field recalculated. That list 
805 will be sent as a parameter for the main function of the field.
806
807 Here's an example from the membership module:
808
809 .. code-block:: python
810
811     'membership_state':
812         fields.function(
813             _membership_state,
814             method=True, 
815             string='Current membership state',
816             type='selection', 
817             selection=STATE,
818             store={
819                 'account.invoice': (_get_invoice_partner, ['state'], 10),
820                 'membership.membership_line': (_get_partner_id,['state'], 10),
821                 'res.partner': (
822                     lambda self, cr, uid, ids, c={}: ids, 
823                     ['free_member'], 
824                     10)
825             }),
826
827 Property Fields
828 +++++++++++++++
829
830 .. describe:: Declaring a property
831
832 A property is a special field: fields.property.
833
834 .. code-block:: python
835
836         class res_partner(osv.osv):
837             _name = "res.partner"
838             _inherit = "res.partner"
839             _columns = {
840                         'property_product_pricelist':
841                                                     fields.property(
842                                         'product.pricelist',
843                                 type='many2one',
844                                 relation='product.pricelist',
845                                 string="Sale Pricelist",
846                                         method=True,
847                                         group_name="Pricelists Properties"),
848             }
849
850
851 Then you have to create the default value in a .XML file for this property:
852
853 .. code-block:: xml
854
855         <record model="ir.property" id="property_product_pricelist">
856             <field name="name">property_product_pricelist</field>
857             <field name="fields_id" search="[('model','=','res.partner'),
858               ('name','=','property_product_pricelist')]"/>
859             <field name="value" eval="'product.pricelist,'+str(list0)"/>
860         </record>
861
862 ..
863
864 .. tip::
865
866         if the default value points to a resource from another module, you can use the ref function like this:
867
868         <field name="value" eval="'product.pricelist,'+str(ref('module.data_id'))"/>
869
870 **Putting properties in forms**
871
872 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
874 Properties are displayed by section, depending on the group_name attribute. (It is rendered in the client like a separator tag).
875
876 **How does this work ?**
877
878 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
880 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
882 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
884 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
886 **Using properties or normal fields**
887
888 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
890
891 Here are a few tips to help you choose between a normal field or a property:
892
893 Normal fields extend the object, adding more features or data.
894
895 A property is a concept that is attached to an object and have special features:
896
897 * Different value for the same property depending on the company
898 * Rights management per field
899 * It's a link between resources (many2one)
900
901 **Example 1: Account Receivable**
902
903 The default "Account Receivable" for a specific partner is implemented as a property because:
904
905     * 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
907     * 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
909     * The default account receivable is the same for all partners and is configured from the general property menu (in administration).
910
911 .. note::
912         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
914 **Example 2: Product Times**
915
916 The product expiry module implements all delays related to products: removal date, product usetime, ... This module is very useful for food industries.
917
918 This module inherits from the product.product object and adds new fields to it:
919
920 .. code-block:: python
921
922         class product_product(osv.osv):
923
924             _inherit = 'product.product'
925             _name = 'product.product'
926             _columns = {
927
928                 'life_time': fields.integer('Product lifetime'),
929                 'use_time': fields.integer('Product usetime'),
930                 'removal_time': fields.integer('Product removal time'),
931                 'alert_time': fields.integer('Product alert time'),
932                 }
933
934         product_product()
935
936 ..
937
938 This module adds simple fields to the product.product object. We did not use properties because:
939
940     * We extend a product, the life_time field is a concept related to a product, not to another object.
941     * We do not need a right management per field, the different delays are managed by the same people that manage all products.
942
943
944 ORM methods
945 -----------
946
947 Keeping the context in ORM methods
948 ++++++++++++++++++++++++++++++++++
949
950 In OpenObject, the context holds very important data such as the language in
951 which a document must be written, whether function field needs updating or not,
952 etc.
953
954 When calling an ORM method, you will probably already have a context - for
955 example the framework will provide you with one as a parameter of almost 
956 every method.
957 If you do have a context, it is very important that you always pass it through
958 to every single method you call.
959
960 This rule also applies to writing ORM methods. You should expect to receive a
961 context as parameter, and always pass it through to every other method you call..