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