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