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