Workaround broken set request in many2many.
[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
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     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
288         obj.datas.setdefault(id, {})
289         obj.datas[id][field] = values
290
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 not isinstance(act,tuple):
519                 print("incorrect values passed in many2many.set:",values)
520                 return
521             if act[0] == 0:
522                 idnew = obj.create(cr, user, act[2])
523                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
524             elif act[0] == 1:
525                 obj.write(cr, user, [act[1]], act[2], context=context)
526             elif act[0] == 2:
527                 obj.unlink(cr, user, [act[1]], context=context)
528             elif act[0] == 3:
529                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
530             elif act[0] == 4:
531                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
532             elif act[0] == 5:
533                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
534             elif act[0] == 6:
535
536                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
537                 if d1:
538                     d1 = ' and ' + d1
539                 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)
540
541                 for act_nbr in act[2]:
542                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
543
544     #
545     # TODO: use a name_search
546     #
547     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
548         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
549
550     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
551         result = {}
552         for id in ids:
553             result[id] = obj.datas[id].get(name, [])
554         return result
555
556     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
557         if not values:
558             return
559         for act in values:
560             # TODO: use constants instead of these magic numbers
561             if act[0] == 0:
562                 raise _('Not Implemented')
563             elif act[0] == 1:
564                 raise _('Not Implemented')
565             elif act[0] == 2:
566                 raise _('Not Implemented')
567             elif act[0] == 3:
568                 raise _('Not Implemented')
569             elif act[0] == 4:
570                 raise _('Not Implemented')
571             elif act[0] == 5:
572                 raise _('Not Implemented')
573             elif act[0] == 6:
574                 obj.datas[id][name] = act[2]
575
576
577 # ---------------------------------------------------------
578 # Function fields
579 # ---------------------------------------------------------
580 class function(_column):
581     _classic_read = False
582     _classic_write = False
583     _type = 'function'
584     _properties = True
585
586 #
587 # multi: compute several fields in one call
588 #
589     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):
590         _column.__init__(self, **args)
591         self._obj = obj
592         self._method = method
593         self._fnct = fnct
594         self._fnct_inv = fnct_inv
595         self._arg = arg
596         self._multi = multi
597         if 'relation' in args:
598             self._obj = args['relation']
599         self._fnct_inv_arg = fnct_inv_arg
600         if not fnct_inv:
601             self.readonly = 1
602         self._type = type
603         self._fnct_search = fnct_search
604         self.store = store
605         if store:
606             self._classic_read = True
607             self._classic_write = True
608             if type=='binary':
609                 self._symbol_get=lambda x:x and str(x)
610
611         if type == 'float':
612             self._symbol_c = float._symbol_c
613             self._symbol_f = float._symbol_f
614             self._symbol_set = float._symbol_set
615
616     def search(self, cr, uid, obj, name, args):
617         if not self._fnct_search:
618             #CHECKME: should raise an exception
619             return []
620         return self._fnct_search(obj, cr, uid, obj, name, args)
621
622     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
623         if not context:
624             context = {}
625         if not values:
626             values = {}
627         res = {}
628         if self._method:
629             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
630         else:
631             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
632
633         if self._type == 'binary' and context.get('bin_size', False):
634             # convert the data returned by the function with the size of that data...
635             res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
636         return res
637
638     def set(self, cr, obj, id, name, value, user=None, context=None):
639         if not context:
640             context = {}
641         if self._fnct_inv:
642             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
643
644 # ---------------------------------------------------------
645 # Related fields
646 # ---------------------------------------------------------
647
648 class related(function):
649
650     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
651         self._field_get2(cr, uid, obj, context)
652         i = len(self._arg)-1
653         sarg = name
654         while i>0:
655             if type(sarg) in [type([]), type( (1,) )]:
656                 where = [(self._arg[i], 'in', sarg)]
657             else:
658                 where = [(self._arg[i], '=', sarg)]
659             if domain:
660                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
661                 domain = []
662             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
663             i -= 1
664         return [(self._arg[0], 'in', sarg)]
665
666     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
667         if values and field_name:
668             self._field_get2(cr, uid, obj, context)
669             relation = obj._name
670             res = {}
671             if type(ids) != type([]):
672                 ids=[ids]
673             objlst = obj.browse(cr, uid, ids)
674             for data in objlst:
675                 t_id=None
676                 t_data = data
677                 relation = obj._name
678                 for i in range(len(self.arg)):
679                     field_detail = self._relations[i]
680                     relation = field_detail['object']
681                     if not t_data[self.arg[i]]:
682                         t_data = False
683                         break
684                     if field_detail['type'] in ('one2many', 'many2many'):
685                         t_id=t_data.id
686                         t_data = t_data[self.arg[i]][0]
687                     else:
688                         t_id=t_data['id']
689                         t_data = t_data[self.arg[i]]
690                 if t_id:
691                     obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values})
692
693     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
694         self._field_get2(cr, uid, obj, context)
695         if not ids: return {}
696         relation = obj._name
697         res = {}.fromkeys(ids, False)
698         objlst = obj.browse(cr, uid, ids)
699         for data in objlst:
700             if not data:
701                 continue
702             t_data = data
703             relation = obj._name
704             for i in range(len(self.arg)):
705                 field_detail = self._relations[i]
706                 relation = field_detail['object']
707                 try:
708                     if not t_data[self.arg[i]]:
709                         t_data = False
710                         break
711                 except:
712                     t_data = False
713                     break
714                 if field_detail['type'] in ('one2many', 'many2many'):
715                     t_data = t_data[self.arg[i]][0]
716                 else:
717                     t_data = t_data[self.arg[i]]
718             if type(t_data) == type(objlst[0]):
719                 res[data.id] = t_data.id
720             else:
721                 res[data.id] = t_data
722
723         if self._type=='many2one':
724             ids = filter(None, res.values())
725             if ids:
726                 ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
727                 for r in res:
728                     if res[r]:
729                         res[r] = (res[r], ng[res[r]])
730         return res
731
732     def __init__(self, *arg, **args):
733         self.arg = arg
734         self._relations = []
735         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
736
737     def _field_get2(self, cr, uid, obj, context={}):
738         if self._relations:
739             return
740         obj_name = obj._name
741         for i in range(len(self._arg)):
742             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
743             self._relations.append({
744                 'object': obj_name,
745                 'type': f['type']
746
747             })
748             if f.get('relation',False):
749                 obj_name = f['relation']
750                 self._relations[-1]['relation'] = f['relation']
751
752 # ---------------------------------------------------------
753 # Serialized fields
754 # ---------------------------------------------------------
755 class serialized(_column):
756     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
757         self._serialize_func = serialize_func
758         self._deserialize_func = deserialize_func
759         self._type = type
760         self._symbol_set = (self._symbol_c, self._serialize_func)
761         self._symbol_get = self._deserialize_func
762         super(serialized, self).__init__(string=string, **args)
763
764
765 class property(function):
766
767     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
768         if not context:
769             context = {}
770         (obj_dest,) = val
771         definition_id = self._field_get(cr, uid, obj._name, prop)
772
773         property = obj.pool.get('ir.property')
774         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
775             ('res_id', '=', obj._name+','+str(id))])
776         while len(nid):
777             cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
778
779         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
780             ('res_id', '=', False)])
781         default_val = False
782         if nid:
783             default_val = property.browse(cr, uid, nid[0], context).value
784
785         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
786         res = False
787         newval = (id_val and obj_dest+','+str(id_val)) or False
788         if (newval != default_val) and newval:
789             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
790                     definition_id, context=context)
791             res = property.create(cr, uid, {
792                 'name': propdef.name,
793                 'value': newval,
794                 'res_id': obj._name+','+str(id),
795                 'company_id': company_id,
796                 'fields_id': definition_id
797             }, context=context)
798         return res
799
800     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
801         if not context:
802             context = {}
803         property = obj.pool.get('ir.property')
804         definition_id = self._field_get(cr, uid, obj._name, prop)
805
806         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
807             ('res_id', '=', False)])
808         default_val = False
809         if nid:
810             d = property.browse(cr, uid, nid[0], context).value
811             default_val = (d and int(d.split(',')[1])) or False
812
813         vids = [obj._name + ',' + str(id) for id in  ids]
814         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
815             ('res_id', 'in', vids)])
816
817         res = {}
818         for id in ids:
819             res[id] = default_val
820         for prop in property.browse(cr, uid, nids):
821             res[int(prop.res_id.split(',')[1])] = (prop.value and \
822                     int(prop.value.split(',')[1])) or False
823
824         obj = obj.pool.get(self._obj)
825         names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
826         for r in res.keys():
827             if res[r] and res[r] in names:
828                 res[r] = (res[r], names[res[r]])
829             else:
830                 res[r] = False
831         return res
832
833     def _field_get(self, cr, uid, model_name, prop):
834         if not self.field_id.get(cr.dbname):
835             cr.execute('SELECT id \
836                     FROM ir_model_fields \
837                     WHERE name=%s AND model=%s', (prop, model_name))
838             res = cr.fetchone()
839             self.field_id[cr.dbname] = res and res[0]
840         return self.field_id[cr.dbname]
841
842     def __init__(self, obj_prop, **args):
843         self.field_id = {}
844         function.__init__(self, self._fnct_read, False, self._fnct_write,
845                 (obj_prop, ), **args)
846
847     def restart(self):
848         self.field_id = {}
849
850
851 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
852