enable get_binary_size for function field witch return binary
[odoo/odoo.git] / bin / osv / fields.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 # . Fields:
32 #      - simple
33 #      - relations (one2many, many2one, many2many)
34 #      - function
35 #
36 # Fields Attributes:
37 #   _classic_read: is a classic sql fields
38 #   _type   : field type
39 #   readonly
40 #   required
41 #   size
42 #
43 import string
44 import netsvc
45
46 import psycopg
47 import warnings
48
49 import tools
50
51
52 def _symbol_set(symb):
53     if symb == None or symb == False:
54         return None
55     elif isinstance(symb, unicode):
56         return symb.encode('utf-8')
57     return str(symb)
58
59
60 class _column(object):
61     _classic_read = True
62     _classic_write = True
63     _properties = False
64     _type = 'unknown'
65     _obj = None
66     _multi = False
67     _symbol_c = '%s'
68     _symbol_f = _symbol_set
69     _symbol_set = (_symbol_c, _symbol_f)
70     _symbol_get = None
71
72     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):
73         self.states = states or {}
74         self.string = string
75         self.readonly = readonly
76         self.required = required
77         self.size = size
78         self.help = args.get('help', '')
79         self.priority = priority
80         self.change_default = change_default
81         self.ondelete = ondelete
82         self.translate = translate
83         self._domain = domain or []
84         self.relate = False
85         self._context = context
86         self.write = False
87         self.read = False
88         self.view_load = 0
89         self.select = select
90         for a in args:
91             if args[a]:
92                 setattr(self, a, args[a])
93         if self.relate:
94             warnings.warn("The relate attribute doesn't work anymore, use act_window tag instead", DeprecationWarning)
95
96     def restart(self):
97         pass
98
99     def set(self, cr, obj, id, name, value, user=None, context=None):
100         cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%d', (self._symbol_set[1](value), id))
101
102     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
103         raise Exception(_('Not implemented set_memory method !'))
104
105     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
106         raise Exception(_('Not implemented get_memory method !'))
107
108     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
109         raise Exception(_('undefined get method !'))
110
111     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
112         ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
113         res = obj.read(cr, uid, ids, [name])
114         return [x[name] for x in res]
115
116     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
117         raise Exception(_('Not implemented search_memory method !'))
118
119
120 # ---------------------------------------------------------
121 # Simple fields
122 # ---------------------------------------------------------
123 class boolean(_column):
124     _type = 'boolean'
125     _symbol_c = '%s'
126     _symbol_f = lambda x: x and 'True' or 'False'
127     _symbol_set = (_symbol_c, _symbol_f)
128
129
130 class integer(_column):
131     _type = 'integer'
132     _symbol_c = '%d'
133     _symbol_f = lambda x: int(x or 0)
134     _symbol_set = (_symbol_c, _symbol_f)
135
136
137 class reference(_column):
138     _type = 'reference'
139
140     def __init__(self, string, selection, size, **args):
141         _column.__init__(self, string=string, size=size, selection=selection, **args)
142
143
144 class char(_column):
145     _type = 'char'
146
147     def __init__(self, string, size, **args):
148         _column.__init__(self, string=string, size=size, **args)
149         self._symbol_set = (self._symbol_c, self._symbol_set_char)
150
151     # takes a string (encoded in utf8) and returns a string (encoded in utf8)
152     def _symbol_set_char(self, symb):
153         #TODO:
154         # * we need to remove the "symb==False" from the next line BUT
155         #   for now too many things rely on this broken behavior
156         # * the symb==None test should be common to all data types
157         if symb == None or symb == False:
158             return None
159
160         # we need to convert the string to a unicode object to be able
161         # to evaluate its length (and possibly truncate it) reliably
162         if isinstance(symb, str):
163             u_symb = unicode(symb, 'utf8')
164         elif isinstance(symb, unicode):
165             u_symb = symb
166         else:
167             u_symb = unicode(symb)
168         return u_symb.encode('utf8')[:self.size]
169
170
171 class text(_column):
172     _type = 'text'
173
174 import __builtin__
175
176
177 class float(_column):
178     _type = 'float'
179     _symbol_c = '%f'
180     _symbol_f = lambda x: __builtin__.float(x or 0.0)
181     _symbol_set = (_symbol_c, _symbol_f)
182
183     def __init__(self, string='unknown', digits=None, **args):
184         _column.__init__(self, string=string, **args)
185         self.digits = digits
186
187
188 class date(_column):
189     _type = 'date'
190
191
192 class datetime(_column):
193     _type = 'datetime'
194
195
196 class time(_column):
197     _type = 'time'
198
199
200 class binary(_column):
201     _type = 'binary'
202     _symbol_c = '%s'
203     _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
204     _symbol_set = (_symbol_c, _symbol_f)
205
206     _classic_read = False
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
214         res = {}
215         for i in ids:
216             val = None
217             for v in values:
218                 if v['id'] == i:
219                     val = v[name]
220                     break
221             res.setdefault(i, val)
222             if context.get('get_binary_size', True):
223                 res[i] = tools.human_size(val) 
224
225         return res
226
227     get = get_memory
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+'=%d where id=%d', (id_new, id))
267         else:
268             cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (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
281     def __init__(self, obj, string='unknown', **args):
282         _column.__init__(self, string=string, **args)
283         self._obj = obj
284
285     #
286     # TODO: speed improvement
287     #
288     # name is the name of the relation field
289     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
290         result = {}
291         for id in ids:
292             result[id] = obj.datas[id][name]
293         return result
294
295     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
296         if not context:
297             context = {}
298         if not values:
299             values = {}
300         res = {}
301         for r in values:
302             res[r['id']] = r[name]
303         for id in ids:
304             res.setdefault(id, '')
305         obj = obj.pool.get(self._obj)
306         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
307         from orm import except_orm
308         try:
309             names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
310         except except_orm:
311             names = {}
312
313             iids = filter(None, res.values())
314             cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
315             for res22 in cr.fetchall():
316                 names[res22[0]] = res22[1]
317
318         for r in res.keys():
319             if res[r] and res[r] in names:
320                 res[r] = (res[r], names[res[r]])
321             else:
322                 res[r] = False
323         return res
324
325     def set(self, cr, obj_src, id, field, values, user=None, context=None):
326         if not context:
327             context = {}
328         obj = obj_src.pool.get(self._obj)
329         self._table = obj_src.pool.get(self._obj)._table
330         if type(values)==type([]):
331             for act in values:
332                 if act[0] == 0:
333                     id_new = obj.create(cr, act[2])
334                     cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
335                 elif act[0] == 1:
336                     obj.write(cr, [act[1]], act[2], context=context)
337                 elif act[0] == 2:
338                     cr.execute('delete from '+self._table+' where id=%d', (act[1],))
339                 elif act[0] == 3 or act[0] == 5:
340                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
341                 elif act[0] == 4:
342                     cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1], id))
343         else:
344             if values:
345                 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values, id))
346             else:
347                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
348
349     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
350         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
351
352
353 class one2many(_column):
354     _classic_read = False
355     _classic_write = False
356     _type = 'one2many'
357
358     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
359         _column.__init__(self, string=string, **args)
360         self._obj = obj
361         self._fields_id = fields_id
362         self._limit = limit
363         #one2many can't be used as condition for defaults
364         assert(self.change_default != True)
365
366     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
367         if not context:
368             context = {}
369         if not values:
370             values = {}
371         res = {}
372         for id in ids:
373             res[id] = []
374         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
375         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
376             if r[self._fields_id] in res:
377                 res[r[self._fields_id]].append(r['id'])
378         return res
379
380     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
381         if not context:
382             context = {}
383         if not values:
384             return
385         obj = obj.pool.get(self._obj)
386         for act in values:
387             if act[0] == 0:
388                 act[2][self._fields_id] = id
389                 obj.create(cr, user, act[2], context=context)
390             elif act[0] == 1:
391                 obj.write(cr, user, [act[1]], act[2], context=context)
392             elif act[0] == 2:
393                 obj.unlink(cr, user, [act[1]], context=context)
394             elif act[0] == 3:
395                 obj.datas[act[1]][self._fields_id] = False
396             elif act[0] == 4:
397                 obj.datas[act[1]] = id
398             elif act[0] == 5:
399                 for o in obj.datas.values():
400                     if o[self._fields_id] == id:
401                         o[self._fields_id] = False
402             elif act[0] == 6:
403                 for id2 in (act[2] or []):
404                     obj.datas[id2][self._fields_id] = id
405
406     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
407         raise _('Not Implemented')
408
409     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
410         if not context:
411             context = {}
412         if not values:
413             values = {}
414         res = {}
415         for id in ids:
416             res[id] = []
417         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
418         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
419             res[r[self._fields_id]].append(r['id'])
420         return res
421
422     def set(self, cr, obj, id, field, values, user=None, context=None):
423         if not context:
424             context = {}
425         if not values:
426             return
427         _table = obj.pool.get(self._obj)._table
428         obj = obj.pool.get(self._obj)
429         for act in values:
430             if act[0] == 0:
431                 act[2][self._fields_id] = id
432                 obj.create(cr, user, act[2], context=context)
433             elif act[0] == 1:
434                 obj.write(cr, user, [act[1]], act[2], context=context)
435             elif act[0] == 2:
436                 obj.unlink(cr, user, [act[1]], context=context)
437             elif act[0] == 3:
438                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
439             elif act[0] == 4:
440                 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id, act[1]))
441             elif act[0] == 5:
442                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
443             elif act[0] == 6:
444                 if not act[2]:
445                     ids2 = [0]
446                 else:
447                     ids2 = act[2]
448                 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
449                 if act[2]:
450                     cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
451
452     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
453         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
454
455
456 #
457 # Values: (0, 0,  { fields })    create
458 #         (1, ID, { fields })    modification
459 #         (2, ID)                remove
460 #         (3, ID)                unlink
461 #         (4, ID)                link
462 #         (5, ID)                unlink all
463 #         (6, ?, ids)            set a list of links
464 #
465 class many2many(_column):
466     _classic_read = False
467     _classic_write = False
468     _type = 'many2many'
469
470     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
471         _column.__init__(self, string=string, **args)
472         self._obj = obj
473         self._rel = rel
474         self._id1 = id1
475         self._id2 = id2
476         self._limit = limit
477
478     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
479         if not context:
480             context = {}
481         if not values:
482             values = {}
483         res = {}
484         if not ids:
485             return res
486         for id in ids:
487             res[id] = []
488         ids_s = ','.join(map(str, ids))
489         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
490         obj = obj.pool.get(self._obj)
491
492         d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
493         if d1:
494             d1 = ' and '+d1
495
496         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
497                 FROM '+self._rel+' , '+obj._table+' \
498                 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
499                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
500                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
501                 d2+[offset])
502         for r in cr.fetchall():
503             res[r[1]].append(r[0])
504         return res
505
506     def set(self, cr, obj, id, name, values, user=None, context=None):
507         if not context:
508             context = {}
509         if not values:
510             return
511         obj = obj.pool.get(self._obj)
512         for act in values:
513             if act[0] == 0:
514                 idnew = obj.create(cr, user, act[2])
515                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, idnew))
516             elif act[0] == 1:
517                 obj.write(cr, user, [act[1]], act[2], context=context)
518             elif act[0] == 2:
519                 obj.unlink(cr, user, [act[1]], context=context)
520             elif act[0] == 3:
521                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id, act[1]))
522             elif act[0] == 4:
523                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, act[1]))
524             elif act[0] == 5:
525                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
526             elif act[0] == 6:
527
528                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
529                 if d1:
530                     d1 = ' and '+d1
531                 cr.execute('delete from '+self._rel+' where '+self._id1+'=%d AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%d AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
532
533                 for act_nbr in act[2]:
534                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
535
536     #
537     # TODO: use a name_search
538     #
539     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
540         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
541
542     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
543         result = {}
544         for id in ids:
545             result[id] = obj.datas[id].get(name, [])
546         return result
547
548     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
549         if not values:
550             return
551         for act in values:
552             # TODO: use constants instead of these magic numbers
553             if act[0] == 0:
554                 raise _('Not Implemented')
555             elif act[0] == 1:
556                 raise _('Not Implemented')
557             elif act[0] == 2:
558                 raise _('Not Implemented')
559             elif act[0] == 3:
560                 raise _('Not Implemented')
561             elif act[0] == 4:
562                 raise _('Not Implemented')
563             elif act[0] == 5:
564                 raise _('Not Implemented')
565             elif act[0] == 6:
566                 obj.datas[id][name] = act[2]
567
568
569 # ---------------------------------------------------------
570 # Function fields
571 # ---------------------------------------------------------
572 class function(_column):
573     _classic_read = False
574     _classic_write = False
575     _type = 'function'
576     _properties = True
577
578 #
579 # multi: compute several fields in one call
580 #
581     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):
582         _column.__init__(self, **args)
583         self._obj = obj
584         self._method = method
585         self._fnct = fnct
586         self._fnct_inv = fnct_inv
587         self._arg = arg
588         self._multi = multi
589         if 'relation' in args:
590             self._obj = args['relation']
591         self._fnct_inv_arg = fnct_inv_arg
592         if not fnct_inv:
593             self.readonly = 1
594         self._type = type
595         self._fnct_search = fnct_search
596         self.store = store
597         if type == 'float':
598             self._symbol_c = '%f'
599             self._symbol_f = lambda x: __builtin__.float(x or 0.0)
600             self._symbol_set = (self._symbol_c, self._symbol_f)
601
602     def search(self, cr, uid, obj, name, args):
603         if not self._fnct_search:
604             #CHECKME: should raise an exception
605             return []
606         return self._fnct_search(obj, cr, uid, obj, name, args)
607
608     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
609         if not context:
610             context = {}
611         if not values:
612             values = {}
613         res = {}
614         if self._method:
615             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
616         else:
617             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
618         
619         if self._type == 'binary' and context.get('get_binary_size', True):
620             # convert the data returned by the function with the size of that data...
621             res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
622         return res
623
624     def set(self, cr, obj, id, name, value, user=None, context=None):
625         if not context:
626             context = {}
627         if self._fnct_inv:
628             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
629
630
631 # ---------------------------------------------------------
632 # Serialized fields
633 # ---------------------------------------------------------
634 class serialized(_column):
635     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
636         self._serialize_func = serialize_func
637         self._deserialize_func = deserialize_func
638         self._type = type
639         self._symbol_set = (self._symbol_c, self._serialize_func)
640         self._symbol_get = self._deserialize_func
641         super(serialized, self).__init__(string=string, **args)
642
643
644 class property(function):
645
646     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
647         if not context:
648             context = {}
649         (obj_dest,) = val
650         definition_id = self._field_get(cr, uid, obj._name, prop)
651
652         property = obj.pool.get('ir.property')
653         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
654             ('res_id', '=', obj._name+','+str(id))])
655         while len(nid):
656             cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
657
658         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
659             ('res_id', '=', False)])
660         default_val = False
661         if nid:
662             default_val = property.browse(cr, uid, nid[0], context).value
663
664         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
665         res = False
666         newval = (id_val and obj_dest+','+str(id_val)) or False
667         if (newval != default_val) and newval:
668             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
669                     definition_id, context=context)
670             res = property.create(cr, uid, {
671                 'name': propdef.name,
672                 'value': newval,
673                 'res_id': obj._name+','+str(id),
674                 'company_id': company_id,
675                 'fields_id': definition_id
676             }, context=context)
677         return res
678
679     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
680         if not context:
681             context = {}
682         property = obj.pool.get('ir.property')
683         definition_id = self._field_get(cr, uid, obj._name, prop)
684
685         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
686             ('res_id', '=', False)])
687         default_val = False
688         if nid:
689             d = property.browse(cr, uid, nid[0], context).value
690             default_val = (d and int(d.split(',')[1])) or False
691
692         vids = [obj._name + ',' + str(id) for id in  ids]
693         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
694             ('res_id', 'in', vids)])
695
696         res = {}
697         for id in ids:
698             res[id] = default_val
699         for prop in property.browse(cr, uid, nids):
700             res[int(prop.res_id.split(',')[1])] = (prop.value and \
701                     int(prop.value.split(',')[1])) or False
702
703         obj = obj.pool.get(self._obj)
704         names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
705         for r in res.keys():
706             if res[r] and res[r] in names:
707                 res[r] = (res[r], names[res[r]])
708             else:
709                 res[r] = False
710         return res
711
712     def _field_get(self, cr, uid, model_name, prop):
713         if not self.field_id.get(cr.dbname):
714             cr.execute('SELECT id \
715                     FROM ir_model_fields \
716                     WHERE name=%s AND model=%s', (prop, model_name))
717             res = cr.fetchone()
718             self.field_id[cr.dbname] = res and res[0]
719         return self.field_id[cr.dbname]
720
721     def __init__(self, obj_prop, **args):
722         self.field_id = {}
723         function.__init__(self, self._fnct_read, False, self._fnct_write,
724                 (obj_prop, ), **args)
725
726     def restart(self):
727         self.field_id = {}
728
729
730 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
731