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