[IMP] Speed impprovement: 2x faster for flow: sale -> invoice -> payment
[odoo/odoo.git] / bin / osv / fields.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 # . Fields:
24 #      - simple
25 #      - relations (one2many, many2one, many2many)
26 #      - function
27 #
28 # Fields Attributes:
29 #   _classic_read: is a classic sql fields
30 #   _type   : field type
31 #   readonly
32 #   required
33 #   size
34 #
35 import string
36 import netsvc
37 import sys
38
39 from psycopg2 import Binary
40 import warnings
41
42 import tools
43
44
45 def _symbol_set(symb):
46     if symb == None or symb == False:
47         return None
48     elif isinstance(symb, unicode):
49         return symb.encode('utf-8')
50     return str(symb)
51
52
53 class _column(object):
54     _classic_read = True
55     _classic_write = True
56     _prefetch = True
57     _properties = False
58     _type = 'unknown'
59     _obj = None
60     _multi = False
61     _symbol_c = '%s'
62     _symbol_f = _symbol_set
63     _symbol_set = (_symbol_c, _symbol_f)
64     _symbol_get = None
65
66     def __init__(self, string='unknown', required=False, readonly=False, domain=None, context='', states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
67         self.states = states or {}
68         self.string = string
69         self.readonly = readonly
70         self.required = required
71         self.size = size
72         self.help = args.get('help', '')
73         self.priority = priority
74         self.change_default = change_default
75         self.ondelete = ondelete
76         self.translate = translate
77         self._domain = domain or []
78         self._context = context
79         self.write = False
80         self.read = False
81         self.view_load = 0
82         self.select = select
83         for a in args:
84             if args[a]:
85                 setattr(self, a, args[a])
86
87     def restart(self):
88         pass
89
90     def set(self, cr, obj, id, name, value, user=None, context=None):
91         cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
92
93     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
94         raise Exception(_('Not implemented set_memory method !'))
95
96     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
97         raise Exception(_('Not implemented get_memory method !'))
98
99     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
100         raise Exception(_('undefined get method !'))
101
102     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
103         ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
104         res = obj.read(cr, uid, ids, [name])
105         return [x[name] for x in res]
106
107     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
108         raise Exception(_('Not implemented search_memory method !'))
109
110
111 # ---------------------------------------------------------
112 # Simple fields
113 # ---------------------------------------------------------
114 class boolean(_column):
115     _type = 'boolean'
116     _symbol_c = '%s'
117     _symbol_f = lambda x: x and 'True' or 'False'
118     _symbol_set = (_symbol_c, _symbol_f)
119
120
121 class integer_big(_column):
122     _type = 'integer_big'
123     _symbol_c = '%s'
124     _symbol_f = lambda x: int(x or 0)
125     _symbol_set = (_symbol_c, _symbol_f)
126
127 class integer(_column):
128     _type = 'integer'
129     _symbol_c = '%s'
130     _symbol_f = lambda x: int(x or 0)
131     _symbol_set = (_symbol_c, _symbol_f)
132
133
134 class reference(_column):
135     _type = 'reference'
136
137     def __init__(self, string, selection, size, **args):
138         _column.__init__(self, string=string, size=size, selection=selection, **args)
139
140
141 class char(_column):
142     _type = 'char'
143
144     def __init__(self, string, size, **args):
145         _column.__init__(self, string=string, size=size, **args)
146         self._symbol_set = (self._symbol_c, self._symbol_set_char)
147
148     # takes a string (encoded in utf8) and returns a string (encoded in utf8)
149     def _symbol_set_char(self, symb):
150         #TODO:
151         # * we need to remove the "symb==False" from the next line BUT
152         #   for now too many things rely on this broken behavior
153         # * the symb==None test should be common to all data types
154         if symb == None or symb == False:
155             return None
156
157         # we need to convert the string to a unicode object to be able
158         # to evaluate its length (and possibly truncate it) reliably
159         u_symb = tools.ustr(symb)
160
161         return u_symb[:self.size].encode('utf8')
162
163
164 class text(_column):
165     _type = 'text'
166
167 import __builtin__
168
169 class float(_column):
170     _type = 'float'
171     _symbol_c = '%s'
172     _symbol_f = lambda x: __builtin__.float(x or 0.0)
173     _symbol_set = (_symbol_c, _symbol_f)
174
175     def __init__(self, string='unknown', digits=None, **args):
176         _column.__init__(self, string=string, **args)
177         self.digits = digits
178
179
180 class date(_column):
181     _type = 'date'
182
183
184 class datetime(_column):
185     _type = 'datetime'
186
187
188 class time(_column):
189     _type = 'time'
190
191
192 class binary(_column):
193     _type = 'binary'
194     _symbol_c = '%s'
195     _symbol_f = lambda symb: symb and Binary(symb) or None
196     _symbol_set = (_symbol_c, _symbol_f)
197     _symbol_get = lambda self, x: x and str(x)
198
199     _classic_read = False
200     _prefetch = False
201
202     def __init__(self, string='unknown', filters=None, **args):
203         _column.__init__(self, string=string, **args)
204         self.filters = filters
205
206     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
207         if not context:
208             context = {}
209         if not values:
210             values = []
211         res = {}
212         for i in ids:
213             val = None
214             for v in values:
215                 if v['id'] == i:
216                     val = v[name]
217                     break
218             if context.get('bin_size', False) and val:
219                 res[i] = tools.human_size(long(val))
220             else:
221                 res[i] = val
222         return res
223
224     get = get_memory
225
226
227 class selection(_column):
228     _type = 'selection'
229
230     def __init__(self, selection, string='unknown', **args):
231         _column.__init__(self, string=string, **args)
232         self.selection = selection
233
234 # ---------------------------------------------------------
235 # Relationals fields
236 # ---------------------------------------------------------
237
238 #
239 # Values: (0, 0,  { fields })    create
240 #         (1, ID, { fields })    modification
241 #         (2, ID)                remove (delete)
242 #         (3, ID)                unlink one (target id or target of relation)
243 #         (4, ID)                link
244 #         (5)                    unlink all (only valid for one2many)
245 #
246 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
247 class one2one(_column):
248     _classic_read = False
249     _classic_write = True
250     _type = 'one2one'
251
252     def __init__(self, obj, string='unknown', **args):
253         warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
254         _column.__init__(self, string=string, **args)
255         self._obj = obj
256
257     def set(self, cr, obj_src, id, field, act, user=None, context=None):
258         if not context:
259             context = {}
260         obj = obj_src.pool.get(self._obj)
261         self._table = obj_src.pool.get(self._obj)._table
262         if act[0] == 0:
263             id_new = obj.create(cr, user, act[1])
264             cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
265         else:
266             cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
267             id = cr.fetchone()[0]
268             obj.write(cr, user, [id], act[1], context=context)
269
270     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
271         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
272
273
274 class many2one(_column):
275     _classic_read = False
276     _classic_write = True
277     _type = 'many2one'
278     _symbol_c = '%s'
279     _symbol_f = lambda x: x or None
280     _symbol_set = (_symbol_c, _symbol_f)
281
282     def __init__(self, obj, string='unknown', **args):
283         _column.__init__(self, string=string, **args)
284         self._obj = obj
285
286     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
287         obj.datas.setdefault(id, {})
288         obj.datas[id][field] = values
289
290     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
291         result = {}
292         for id in ids:
293             result[id] = obj.datas[id][name]
294         return result
295
296     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
297         if not context:
298             context = {}
299         if not values:
300             values = {}
301         res = {}
302         for r in values:
303             res[r['id']] = r[name]
304         for id in ids:
305             res.setdefault(id, '')
306         obj = obj.pool.get(self._obj)
307         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
308         from orm import except_orm
309         try:
310             names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
311         except except_orm:
312             names = {}
313             iids = filter(None, res.values())
314             for iiid in iids:
315                 names[iiid] = '// Access Denied //'
316
317         for r in res.keys():
318             if res[r] and res[r] in names:
319                 res[r] = (res[r], names[res[r]])
320             else:
321                 res[r] = False
322         return res
323
324     def set(self, cr, obj_src, id, field, values, user=None, context=None):
325         if not context:
326             context = {}
327         obj = obj_src.pool.get(self._obj)
328         self._table = obj_src.pool.get(self._obj)._table
329         if type(values) == type([]):
330             for act in values:
331                 if act[0] == 0:
332                     id_new = obj.create(cr, act[2])
333                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
334                 elif act[0] == 1:
335                     obj.write(cr, [act[1]], act[2], context=context)
336                 elif act[0] == 2:
337                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
338                 elif act[0] == 3 or act[0] == 5:
339                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
340                 elif act[0] == 4:
341                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
342         else:
343             if values:
344                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
345             else:
346                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
347
348     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
349         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
350
351
352 class one2many(_column):
353     _classic_read = False
354     _classic_write = False
355     _prefetch = False
356     _type = 'one2many'
357
358     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
359         _column.__init__(self, string=string, **args)
360         self._obj = obj
361         self._fields_id = fields_id
362         self._limit = limit
363         #one2many can't be used as condition for defaults
364         assert(self.change_default != True)
365
366     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
367         if not context:
368             context = {}
369         if self._context:
370             context = context.copy()
371             context.update(self._context)
372         if not values:
373             values = {}
374         res = {}
375         for id in ids:
376             res[id] = []
377         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
378         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
379             if r[self._fields_id] in res:
380                 res[r[self._fields_id]].append(r['id'])
381         return res
382
383     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
384         if not context:
385             context = {}
386         if self._context:
387             context = context.copy()
388         context.update(self._context)
389         if not values:
390             return
391         obj = obj.pool.get(self._obj)
392         for act in values:
393             if act[0] == 0:
394                 act[2][self._fields_id] = id
395                 obj.create(cr, user, act[2], context=context)
396             elif act[0] == 1:
397                 obj.write(cr, user, [act[1]], act[2], context=context)
398             elif act[0] == 2:
399                 obj.unlink(cr, user, [act[1]], context=context)
400             elif act[0] == 3:
401                 obj.datas[act[1]][self._fields_id] = False
402             elif act[0] == 4:
403                 obj.datas[act[1]] = id
404             elif act[0] == 5:
405                 for o in obj.datas.values():
406                     if o[self._fields_id] == id:
407                         o[self._fields_id] = False
408             elif act[0] == 6:
409                 for id2 in (act[2] or []):
410                     obj.datas[id2][self._fields_id] = id
411
412     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
413         raise _('Not Implemented')
414
415     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
416         if not context:
417             context = {}
418         if self._context:
419             context = context.copy()
420         context.update(self._context)
421         if not values:
422             values = {}
423         res = {}
424         for id in ids:
425             res[id] = []
426         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
427         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
428             res[r[self._fields_id]].append(r['id'])
429         return res
430
431     def set(self, cr, obj, id, field, values, user=None, context=None):
432         result = []
433         if not context:
434             context = {}
435         if self._context:
436             context = context.copy()
437         context.update(self._context)
438         context['no_store_function'] = True
439         if not values:
440             return
441         _table = obj.pool.get(self._obj)._table
442         obj = obj.pool.get(self._obj)
443         for act in values:
444             if act[0] == 0:
445                 act[2][self._fields_id] = id
446                 id_new = obj.create(cr, user, act[2], context=context)
447                 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
448             elif act[0] == 1:
449                 obj.write(cr, user, [act[1]], act[2], context=context)
450             elif act[0] == 2:
451                 obj.unlink(cr, user, [act[1]], context=context)
452             elif act[0] == 3:
453                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
454             elif act[0] == 4:
455                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
456             elif act[0] == 5:
457                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
458             elif act[0] == 6:
459                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
460                 ids2 = act[2] or [0]
461                 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id not in ('+','.join(map(str, ids2))+')', (id,))
462                 ids3 = map(lambda x:x[0], cr.fetchall())
463                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
464         return result
465
466     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
467         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
468
469
470 #
471 # Values: (0, 0,  { fields })    create
472 #         (1, ID, { fields })    modification
473 #         (2, ID)                remove
474 #         (3, ID)                unlink
475 #         (4, ID)                link
476 #         (5, ID)                unlink all
477 #         (6, ?, ids)            set a list of links
478 #
479 class many2many(_column):
480     _classic_read = False
481     _classic_write = False
482     _prefetch = False
483     _type = 'many2many'
484
485     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
486         _column.__init__(self, string=string, **args)
487         self._obj = obj
488         if '.' in rel:
489             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
490                 'You used %s, which is not a valid SQL table name.')% (string,rel))
491         self._rel = rel
492         self._id1 = id1
493         self._id2 = id2
494         self._limit = limit
495
496     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
497         if not context:
498             context = {}
499         if not values:
500             values = {}
501         res = {}
502         if not ids:
503             return res
504         for id in ids:
505             res[id] = []
506         ids_s = ','.join(map(str, ids))
507         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
508         obj = obj.pool.get(self._obj)
509
510         d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
511         if d1:
512             d1 = ' and ' + d1
513
514         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
515                 FROM '+self._rel+' , '+obj._table+' \
516                 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
517                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
518                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
519                 d2+[offset])
520         for r in cr.fetchall():
521             res[r[1]].append(r[0])
522         return res
523
524     def set(self, cr, obj, id, name, values, user=None, context=None):
525         if not context:
526             context = {}
527         if not values:
528             return
529         obj = obj.pool.get(self._obj)
530         for act in values:
531             if act[0] == 0:
532                 idnew = obj.create(cr, user, act[2])
533                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
534             elif act[0] == 1:
535                 obj.write(cr, user, [act[1]], act[2], context=context)
536             elif act[0] == 2:
537                 obj.unlink(cr, user, [act[1]], context=context)
538             elif act[0] == 3:
539                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
540             elif act[0] == 4:
541                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
542             elif act[0] == 5:
543                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
544             elif act[0] == 6:
545
546                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
547                 if d1:
548                     d1 = ' and ' + d1
549                 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
550
551                 for act_nbr in act[2]:
552                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
553
554     #
555     # TODO: use a name_search
556     #
557     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
558         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
559
560     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
561         result = {}
562         for id in ids:
563             result[id] = obj.datas[id].get(name, [])
564         return result
565
566     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
567         if not values:
568             return
569         for act in values:
570             # TODO: use constants instead of these magic numbers
571             if act[0] == 0:
572                 raise _('Not Implemented')
573             elif act[0] == 1:
574                 raise _('Not Implemented')
575             elif act[0] == 2:
576                 raise _('Not Implemented')
577             elif act[0] == 3:
578                 raise _('Not Implemented')
579             elif act[0] == 4:
580                 raise _('Not Implemented')
581             elif act[0] == 5:
582                 raise _('Not Implemented')
583             elif act[0] == 6:
584                 obj.datas[id][name] = act[2]
585
586
587 # ---------------------------------------------------------
588 # Function fields
589 # ---------------------------------------------------------
590 class function(_column):
591     _classic_read = False
592     _classic_write = False
593     _prefetch = False
594     _type = 'function'
595     _properties = True
596
597 #
598 # multi: compute several fields in one call
599 #
600     def __init__(self, fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, method=False, store=False, multi=False, **args):
601         _column.__init__(self, **args)
602         self._obj = obj
603         self._method = method
604         self._fnct = fnct
605         self._fnct_inv = fnct_inv
606         self._arg = arg
607         self._multi = multi
608         if 'relation' in args:
609             self._obj = args['relation']
610         self._fnct_inv_arg = fnct_inv_arg
611         if not fnct_inv:
612             self.readonly = 1
613         self._type = type
614         self._fnct_search = fnct_search
615         self.store = store
616         if store:
617             self._classic_read = True
618             self._classic_write = True
619             if type=='binary':
620                 self._symbol_get=lambda x:x and str(x)
621
622         if type == 'float':
623             self._symbol_c = float._symbol_c
624             self._symbol_f = float._symbol_f
625             self._symbol_set = float._symbol_set
626
627     def search(self, cr, uid, obj, name, args):
628         if not self._fnct_search:
629             #CHECKME: should raise an exception
630             return []
631         return self._fnct_search(obj, cr, uid, obj, name, args)
632
633     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
634         if not context:
635             context = {}
636         if not values:
637             values = {}
638         res = {}
639         if self._method:
640             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
641         else:
642             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
643
644         if self._type == 'binary' and context.get('bin_size', False):
645             # convert the data returned by the function with the size of that data...
646             res = dict(map(lambda (x, y): (x, tools.human_size(len(y or ''))), res.items()))
647         return res
648     get_memory = get
649
650     def set(self, cr, obj, id, name, value, user=None, context=None):
651         if not context:
652             context = {}
653         if self._fnct_inv:
654             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
655     set_memory = set
656
657 # ---------------------------------------------------------
658 # Related fields
659 # ---------------------------------------------------------
660
661 class related(function):
662
663     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
664         self._field_get2(cr, uid, obj, context)
665         i = len(self._arg)-1
666         sarg = name
667         while i>0:
668             if type(sarg) in [type([]), type( (1,) )]:
669                 where = [(self._arg[i], 'in', sarg)]
670             else:
671                 where = [(self._arg[i], '=', sarg)]
672             if domain:
673                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
674                 domain = []
675             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
676             i -= 1
677         return [(self._arg[0], 'in', sarg)]
678
679     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
680         if values and field_name:
681             self._field_get2(cr, uid, obj, context)
682             relation = obj._name
683             res = {}
684             if type(ids) != type([]):
685                 ids=[ids]
686             objlst = obj.browse(cr, uid, ids)
687             for data in objlst:
688                 t_id=None
689                 t_data = data
690                 relation = obj._name
691                 for i in range(len(self.arg)):
692                     field_detail = self._relations[i]
693                     relation = field_detail['object']
694                     if not t_data[self.arg[i]]:
695                         t_data = False
696                         break
697                     if field_detail['type'] in ('one2many', 'many2many'):
698                         if self._type != "many2one":
699                             t_id=t_data.id
700                             t_data = t_data[self.arg[i]][0]
701                     else:
702                         t_id=t_data['id']
703                         t_data = t_data[self.arg[i]]
704                 if t_id:
705                     obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values})
706
707     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
708         self._field_get2(cr, uid, obj, context)
709         if not ids: return {}
710         relation = obj._name
711         res = {}.fromkeys(ids, False)
712         objlst = obj.browse(cr, uid, ids)
713         for data in objlst:
714             if not data:
715                 continue
716             t_data = data
717             relation = obj._name
718             for i in range(len(self.arg)):
719                 field_detail = self._relations[i]
720                 relation = field_detail['object']
721                 try:
722                     if not t_data[self.arg[i]]:
723                         t_data = False
724                         break
725                 except:
726                     t_data = False
727                     break
728                 if field_detail['type'] in ('one2many', 'many2many'):
729                     t_data = t_data[self.arg[i]][0]
730                 else:
731                     t_data = t_data[self.arg[i]]
732             if type(t_data) == type(objlst[0]):
733                 res[data.id] = t_data.id
734             else:
735                 res[data.id] = t_data
736
737         if self._type=='many2one':
738             ids = filter(None, res.values())
739             if ids:
740                 ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
741                 for r in res:
742                     if res[r]:
743                         res[r] = (res[r], ng[res[r]])
744         return res
745
746     def __init__(self, *arg, **args):
747         self.arg = arg
748         self._relations = []
749         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
750
751     def _field_get2(self, cr, uid, obj, context={}):
752         if self._relations:
753             return
754         obj_name = obj._name
755         for i in range(len(self._arg)):
756             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
757             self._relations.append({
758                 'object': obj_name,
759                 'type': f['type']
760
761             })
762             if f.get('relation',False):
763                 obj_name = f['relation']
764                 self._relations[-1]['relation'] = f['relation']
765
766 # ---------------------------------------------------------
767 # Serialized fields
768 # ---------------------------------------------------------
769 class serialized(_column):
770     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
771         self._serialize_func = serialize_func
772         self._deserialize_func = deserialize_func
773         self._type = type
774         self._symbol_set = (self._symbol_c, self._serialize_func)
775         self._symbol_get = self._deserialize_func
776         super(serialized, self).__init__(string=string, **args)
777
778
779 class property(function):
780
781     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
782         if not context:
783             context = {}
784         (obj_dest,) = val
785         definition_id = self._field_get(cr, uid, obj._name, prop)
786
787         property = obj.pool.get('ir.property')
788         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
789             ('res_id', '=', obj._name+','+str(id))])
790         while len(nid):
791             cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
792
793         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
794             ('res_id', '=', False)])
795         default_val = False
796         if nid:
797             default_val = property.browse(cr, uid, nid[0], context).value
798
799         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
800         res = False
801         newval = (id_val and obj_dest+','+str(id_val)) or False
802         if (newval != default_val) and newval:
803             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
804                     definition_id, context=context)
805             res = property.create(cr, uid, {
806                 'name': propdef.name,
807                 'value': newval,
808                 'res_id': obj._name+','+str(id),
809                 'company_id': company_id,
810                 'fields_id': definition_id
811             }, context=context)
812         return res
813
814     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
815         if not context:
816             context = {}
817         property = obj.pool.get('ir.property')
818         definition_id = self._field_get(cr, uid, obj._name, prop)
819
820         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
821             ('res_id', '=', False)])
822         default_val = False
823         if nid:
824             d = property.browse(cr, uid, nid[0], context).value
825             default_val = (d and int(d.split(',')[1])) or False
826
827         vids = [obj._name + ',' + str(id) for id in  ids]
828         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
829             ('res_id', 'in', vids)])
830
831         res = {}
832         for id in ids:
833             res[id] = default_val
834         for prop in property.browse(cr, uid, nids):
835             res[int(prop.res_id.split(',')[1])] = (prop.value and \
836                     int(prop.value.split(',')[1])) or False
837
838         obj = obj.pool.get(self._obj)
839
840         to_check = res.values()
841         if default_val and default_val not in to_check:
842             to_check += [default_val]
843         existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
844         
845         for id, res_id in res.items():
846             if res_id not in existing_ids:
847                 cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
848                 res[id] = default_val
849
850         names = dict(obj.name_get(cr, uid, existing_ids, context))
851         for r in res.keys():
852             if res[r] and res[r] in names:
853                 res[r] = (res[r], names[res[r]])
854             else:
855                 res[r] = False
856         return res
857
858     def _field_get(self, cr, uid, model_name, prop):
859         if not self.field_id.get(cr.dbname):
860             cr.execute('SELECT id \
861                     FROM ir_model_fields \
862                     WHERE name=%s AND model=%s', (prop, model_name))
863             res = cr.fetchone()
864             self.field_id[cr.dbname] = res and res[0]
865         return self.field_id[cr.dbname]
866
867     def __init__(self, obj_prop, **args):
868         self.field_id = {}
869         function.__init__(self, self._fnct_read, False, self._fnct_write,
870                 (obj_prop, ), **args)
871
872     def restart(self):
873         self.field_id = {}
874
875
876 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
877