1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
24 # - relations (one2many, many2one, many2many)
28 # _classic_read: is a classic sql fields
40 from psycopg2 import Binary
43 from tools.translate import _
45 def _symbol_set(symb):
46 if symb == None or symb == False:
48 elif isinstance(symb, unicode):
49 return symb.encode('utf-8')
53 class _column(object):
62 _symbol_f = _symbol_set
63 _symbol_set = (_symbol_c, _symbol_f)
66 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):
69 self.states = states or {}
71 self.readonly = readonly
72 self.required = required
74 self.help = args.get('help', '')
75 self.priority = priority
76 self.change_default = change_default
77 self.ondelete = ondelete
78 self.translate = translate
79 self._domain = domain or []
80 self._context = context
85 self.selectable = True
86 self.group_operator = args.get('group_operator', False)
89 setattr(self, a, args[a])
94 def set(self, cr, obj, id, name, value, user=None, context=None):
95 cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
97 def set_memory(self, cr, obj, id, name, value, user=None, context=None):
98 raise Exception(_('Not implemented set_memory method !'))
100 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
101 raise Exception(_('Not implemented get_memory method !'))
103 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
104 raise Exception(_('undefined get method !'))
106 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
107 ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
108 res = obj.read(cr, uid, ids, [name], context=context)
109 return [x[name] for x in res]
111 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
112 raise Exception(_('Not implemented search_memory method !'))
115 # ---------------------------------------------------------
117 # ---------------------------------------------------------
118 class boolean(_column):
121 _symbol_f = lambda x: x and 'True' or 'False'
122 _symbol_set = (_symbol_c, _symbol_f)
124 class integer_big(_column):
125 _type = 'integer_big'
127 _symbol_f = lambda x: int(x or 0)
128 _symbol_set = (_symbol_c, _symbol_f)
129 _symbol_get = lambda self,x: x or 0
131 class integer(_column):
134 _symbol_f = lambda x: int(x or 0)
135 _symbol_set = (_symbol_c, _symbol_f)
136 _symbol_get = lambda self,x: x or 0
139 class reference(_column):
141 def __init__(self, string, selection, size, **args):
142 _column.__init__(self, string=string, size=size, selection=selection, **args)
148 def __init__(self, string, size, **args):
149 _column.__init__(self, string=string, size=size, **args)
150 self._symbol_set = (self._symbol_c, self._symbol_set_char)
152 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
153 def _symbol_set_char(self, symb):
155 # * we need to remove the "symb==False" from the next line BUT
156 # for now too many things rely on this broken behavior
157 # * the symb==None test should be common to all data types
158 if symb == None or symb == False:
161 # we need to convert the string to a unicode object to be able
162 # to evaluate its length (and possibly truncate it) reliably
163 u_symb = tools.ustr(symb)
165 return u_symb[:self.size].encode('utf8')
173 class float(_column):
176 _symbol_f = lambda x: __builtin__.float(x or 0.0)
177 _symbol_set = (_symbol_c, _symbol_f)
178 _symbol_get = lambda self,x: x or 0.0
180 def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
181 _column.__init__(self, string=string, **args)
183 self.digits_compute = digits_compute
186 def digits_change(self, cr):
187 if self.digits_compute:
188 t = self.digits_compute(cr)
189 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
196 """ Returns the current date in a format fit for being a
197 default value to a ``date`` field.
199 This method should be provided as is to the _defaults dict, it
200 should not be called.
202 return DT.date.today().strftime(
203 tools.DEFAULT_SERVER_DATE_FORMAT)
205 class datetime(_column):
209 """ Returns the current datetime in a format fit for being a
210 default value to a ``datetime`` field.
212 This method should be provided as is to the _defaults dict, it
213 should not be called.
215 return DT.datetime.now().strftime(
216 tools.DEFAULT_SERVER_DATETIME_FORMAT)
222 """ Returns the current time in a format fit for being a
223 default value to a ``time`` field.
225 This method should be proivided as is to the _defaults dict,
226 it should not be called.
228 return DT.datetime.now().strftime(
229 tools.DEFAULT_SERVER_TIME_FORMAT)
231 class binary(_column):
234 _symbol_f = lambda symb: symb and Binary(symb) or None
235 _symbol_set = (_symbol_c, _symbol_f)
236 _symbol_get = lambda self, x: x and str(x)
238 _classic_read = False
241 def __init__(self, string='unknown', filters=None, **args):
242 _column.__init__(self, string=string, **args)
243 self.filters = filters
245 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
257 if context.get('bin_size', False) and val:
258 res[i] = tools.human_size(long(val))
266 class selection(_column):
269 def __init__(self, selection, string='unknown', **args):
270 _column.__init__(self, string=string, **args)
271 self.selection = selection
273 # ---------------------------------------------------------
275 # ---------------------------------------------------------
278 # Values: (0, 0, { fields }) create
279 # (1, ID, { fields }) update
280 # (2, ID) remove (delete)
281 # (3, ID) unlink one (target id or target of relation)
283 # (5) unlink all (only valid for one2many)
285 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
286 class one2one(_column):
287 _classic_read = False
288 _classic_write = True
291 def __init__(self, obj, string='unknown', **args):
292 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
293 _column.__init__(self, string=string, **args)
296 def set(self, cr, obj_src, id, field, act, user=None, context=None):
299 obj = obj_src.pool.get(self._obj)
300 self._table = obj_src.pool.get(self._obj)._table
302 id_new = obj.create(cr, user, act[1])
303 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
305 cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
306 id = cr.fetchone()[0]
307 obj.write(cr, user, [id], act[1], context=context)
309 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
310 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
313 class many2one(_column):
314 _classic_read = False
315 _classic_write = True
318 _symbol_f = lambda x: x or None
319 _symbol_set = (_symbol_c, _symbol_f)
321 def __init__(self, obj, string='unknown', **args):
322 _column.__init__(self, string=string, **args)
325 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
326 obj.datas.setdefault(id, {})
327 obj.datas[id][field] = values
329 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
332 result[id] = obj.datas[id].get(name, False)
335 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
336 context = context or {}
337 values = values or {}
341 res[r['id']] = r[name]
343 res.setdefault(id, '')
344 obj = obj.pool.get(self._obj)
346 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
347 # we use uid=1 because the visibility of a many2one field value (just id and name)
348 # must be the access right of the parent form and not the linked object itself.
349 records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
351 if res[id] in records:
352 res[id] = (res[id], records[res[id]])
357 def set(self, cr, obj_src, id, field, values, user=None, context=None):
360 obj = obj_src.pool.get(self._obj)
361 self._table = obj_src.pool.get(self._obj)._table
362 if type(values) == type([]):
365 id_new = obj.create(cr, act[2])
366 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
368 obj.write(cr, [act[1]], act[2], context=context)
370 cr.execute('delete from '+self._table+' where id=%s', (act[1],))
371 elif act[0] == 3 or act[0] == 5:
372 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
374 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
377 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
379 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
381 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
382 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
385 class one2many(_column):
386 _classic_read = False
387 _classic_write = False
391 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
392 _column.__init__(self, string=string, **args)
394 self._fields_id = fields_id
396 #one2many can't be used as condition for defaults
397 assert(self.change_default != True)
399 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
403 context = context.copy()
404 context.update(self._context)
410 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
411 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
412 if r[self._fields_id] in res:
413 res[r[self._fields_id]].append(r['id'])
416 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
420 context = context.copy()
421 context.update(self._context)
424 obj = obj.pool.get(self._obj)
427 act[2][self._fields_id] = id
428 obj.create(cr, user, act[2], context=context)
430 obj.write(cr, user, [act[1]], act[2], context=context)
432 obj.unlink(cr, user, [act[1]], context=context)
434 obj.datas[act[1]][self._fields_id] = False
436 obj.datas[act[1]] = id
438 for o in obj.datas.values():
439 if o[self._fields_id] == id:
440 o[self._fields_id] = False
442 for id2 in (act[2] or []):
443 obj.datas[id2][self._fields_id] = id
445 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
446 raise _('Not Implemented')
448 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
452 context = context.copy()
453 context.update(self._context)
461 ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
462 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
463 if r[self._fields_id] in res:
464 res[r[self._fields_id]].append(r['id'])
467 def set(self, cr, obj, id, field, values, user=None, context=None):
472 context = context.copy()
473 context.update(self._context)
474 context['no_store_function'] = True
477 _table = obj.pool.get(self._obj)._table
478 obj = obj.pool.get(self._obj)
481 act[2][self._fields_id] = id
482 id_new = obj.create(cr, user, act[2], context=context)
483 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
485 obj.write(cr, user, [act[1]], act[2], context=context)
487 obj.unlink(cr, user, [act[1]], context=context)
489 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
491 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
493 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
495 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
497 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
498 ids3 = map(lambda x:x[0], cr.fetchall())
499 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
502 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
503 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
507 # Values: (0, 0, { fields }) create
508 # (1, ID, { fields }) update (write fields to ID)
509 # (2, ID) remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
510 # (3, ID) unlink (delete the relationship between the two objects but does not delete ID)
511 # (4, ID) link (add a relationship)
513 # (6, ?, ids) set a list of links
515 class many2many(_column):
516 _classic_read = False
517 _classic_write = False
520 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
521 _column.__init__(self, string=string, **args)
524 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
525 'You used %s, which is not a valid SQL table name.')% (string,rel))
531 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
542 warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.",
543 DeprecationWarning, stacklevel=2)
544 obj = obj.pool.get(self._obj)
546 # static domains are lists, and are evaluated both here and on client-side, while string
547 # domains supposed by dynamic and evaluated on client-side only (thus ignored here)
548 # FIXME: make this distinction explicit in API!
549 domain = isinstance(self._domain, list) and self._domain or []
551 wquery = obj._where_calc(cr, user, domain, context=context)
552 obj._apply_ir_rules(cr, user, wquery, 'read', context=context)
553 from_c, where_c, where_params = wquery.get_sql()
555 where_c = ' AND ' + where_c
557 if offset or self._limit:
558 order_by = ' ORDER BY "%s".%s' %(obj._table, obj._order.split(',')[0])
563 if self._limit is not None:
564 limit_str = ' LIMIT %d' % self._limit
566 query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
567 FROM %(rel)s, %(from_c)s \
568 WHERE %(rel)s.%(id1)s IN %%s \
569 AND %(rel)s.%(id2)s = %(tbl)s.id \
581 'order_by': order_by,
584 cr.execute(query, [tuple(ids),] + where_params)
585 for r in cr.fetchall():
586 res[r[1]].append(r[0])
589 def set(self, cr, obj, id, name, values, user=None, context=None):
594 obj = obj.pool.get(self._obj)
596 if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
599 idnew = obj.create(cr, user, act[2])
600 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
602 obj.write(cr, user, [act[1]], act[2], context=context)
604 obj.unlink(cr, user, [act[1]], context=context)
606 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
608 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
610 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
613 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
615 d1 = ' and ' + ' and '.join(d1)
618 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+','.join(tables)+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
620 for act_nbr in act[2]:
621 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
624 # TODO: use a name_search
626 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
627 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
629 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
632 result[id] = obj.datas[id].get(name, [])
635 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
639 # TODO: use constants instead of these magic numbers
641 raise _('Not Implemented')
643 raise _('Not Implemented')
645 raise _('Not Implemented')
647 raise _('Not Implemented')
649 raise _('Not Implemented')
651 raise _('Not Implemented')
653 obj.datas[id][name] = act[2]
656 def get_nice_size(a):
658 if isinstance(y, (int,long)):
664 return (x, tools.human_size(size))
666 # ---------------------------------------------------------
668 # ---------------------------------------------------------
669 class function(_column):
670 _classic_read = False
671 _classic_write = False
677 # multi: compute several fields in one call
679 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):
680 _column.__init__(self, **args)
682 self._method = method
684 self._fnct_inv = fnct_inv
687 if 'relation' in args:
688 self._obj = args['relation']
690 self.digits = args.get('digits', (16,2))
691 self.digits_compute = args.get('digits_compute', None)
693 self._fnct_inv_arg = fnct_inv_arg
697 self._fnct_search = fnct_search
700 if not fnct_search and not store:
701 self.selectable = False
704 if self._type != 'many2one':
705 # m2o fields need to return tuples with name_get, not just foreign keys
706 self._classic_read = True
707 self._classic_write = True
709 self._symbol_get=lambda x:x and str(x)
712 self._symbol_c = float._symbol_c
713 self._symbol_f = float._symbol_f
714 self._symbol_set = float._symbol_set
716 if type == 'boolean':
717 self._symbol_c = boolean._symbol_c
718 self._symbol_f = boolean._symbol_f
719 self._symbol_set = boolean._symbol_set
721 def digits_change(self, cr):
722 if self.digits_compute:
723 t = self.digits_compute(cr)
724 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
728 def search(self, cr, uid, obj, name, args, context=None):
729 if not self._fnct_search:
730 #CHECKME: should raise an exception
732 return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
734 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
741 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
743 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
745 if self._type == "many2one" :
746 # Filtering only integer/long values if passed
747 res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
750 obj_model = obj.pool.get(self._obj)
751 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
753 if res[r] and res[r] in dict_names:
754 res[r] = (res[r], dict_names[res[r]])
756 if self._type == 'binary' and context.get('bin_size', False):
757 # convert the data returned by the function with the size of that data...
758 res = dict(map( get_nice_size, res.items()))
759 if self._type == "integer":
761 # Converting value into string so that it does not affect XML-RPC Limits
762 if isinstance(res[r],dict): # To treat integer values with _multi attribute
763 for record in res[r].keys():
764 res[r][record] = str(res[r][record])
770 def set(self, cr, obj, id, name, value, user=None, context=None):
774 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
777 # ---------------------------------------------------------
779 # ---------------------------------------------------------
781 class related(function):
783 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
784 self._field_get2(cr, uid, obj, context)
788 if type(sarg) in [type([]), type( (1,) )]:
789 where = [(self._arg[i], 'in', sarg)]
791 where = [(self._arg[i], '=', sarg)]
793 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
795 sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
797 return [(self._arg[0], 'in', sarg)]
799 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
800 self._field_get2(cr, uid, obj, context)
801 if type(ids) != type([]):
803 objlst = obj.browse(cr, uid, ids)
807 for i in range(len(self.arg)):
809 field_detail = self._relations[i]
810 if not t_data[self.arg[i]]:
811 if self._type not in ('one2many', 'many2many'):
814 elif field_detail['type'] in ('one2many', 'many2many'):
815 if self._type != "many2one":
817 t_data = t_data[self.arg[i]][0]
822 t_data = t_data[self.arg[i]]
824 model = obj.pool.get(self._relations[-1]['object'])
825 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
827 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
828 self._field_get2(cr, uid, obj, context)
829 if not ids: return {}
831 if self._type in ('one2many', 'many2many'):
832 res = dict([(i, []) for i in ids])
834 res = {}.fromkeys(ids, False)
836 objlst = obj.browse(cr, 1, ids, context=context)
842 for i in range(len(self.arg)):
843 field_detail = self._relations[i]
844 relation = field_detail['object']
846 if not t_data[self.arg[i]]:
852 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
853 t_data = t_data[self.arg[i]][0]
855 t_data = t_data[self.arg[i]]
856 if type(t_data) == type(objlst[0]):
857 res[data.id] = t_data.id
859 res[data.id] = t_data
860 if self._type=='many2one':
861 ids = filter(None, res.values())
863 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
866 res[r] = (res[r], ng[res[r]])
867 elif self._type in ('one2many', 'many2many'):
870 res[r] = [x.id for x in res[r]]
873 def __init__(self, *arg, **args):
876 super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
877 if self.store is True:
878 # TODO: improve here to change self.store = {...} according to related objects
881 def _field_get2(self, cr, uid, obj, context={}):
885 for i in range(len(self._arg)):
886 f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
887 self._relations.append({
892 if f.get('relation',False):
893 obj_name = f['relation']
894 self._relations[-1]['relation'] = f['relation']
896 # ---------------------------------------------------------
898 # ---------------------------------------------------------
900 class dummy(function):
901 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
904 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
907 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
910 def __init__(self, *arg, **args):
913 super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
915 # ---------------------------------------------------------
917 # ---------------------------------------------------------
918 class serialized(_column):
919 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
920 self._serialize_func = serialize_func
921 self._deserialize_func = deserialize_func
923 self._symbol_set = (self._symbol_c, self._serialize_func)
924 self._symbol_get = self._deserialize_func
925 super(serialized, self).__init__(string=string, **args)
928 # TODO: review completly this class for speed improvement
929 class property(function):
931 def _get_default(self, obj, cr, uid, prop_name, context=None):
932 return self._get_defaults(obj, cr, uid, [prop_name], context=None)[0][prop_name]
934 def _get_defaults(self, obj, cr, uid, prop_name, context=None):
935 prop = obj.pool.get('ir.property')
936 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
937 ids = prop.search(cr, uid, domain, context=context)
939 default_value = {}.fromkeys(prop_name, False)
940 for prop_rec in prop.browse(cr, uid, ids, context=context):
941 if default_value.get(prop_rec.fields_id.name, False):
943 value = prop.get_by_record(cr, uid, prop_rec, context=context) or False
944 default_value[prop_rec.fields_id.name] = value
945 if value and (prop_rec.type == 'many2one'):
946 replaces.setdefault(value._name, {})
947 replaces[value._name][value.id] = True
948 return default_value, replaces
950 def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
951 prop = obj.pool.get('ir.property')
952 vids = [obj._name + ',' + str(oid) for oid in ids]
954 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
955 #domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
957 domain = [('res_id', 'in', vids)] + domain
958 return prop.search(cr, uid, domain, context=context)
960 # TODO: to rewrite more clean
961 def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
965 nids = self._get_by_id(obj, cr, uid, [prop_name], [id], context)
967 cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
969 default_val = self._get_default(obj, cr, uid, prop_name, context)
971 if id_val is not default_val:
972 def_id = self._field_get(cr, uid, obj._name, prop_name)
973 company = obj.pool.get('res.company')
974 cid = company._company_default_get(cr, uid, obj._name, def_id,
976 propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
978 prop = obj.pool.get('ir.property')
979 return prop.create(cr, uid, {
980 'name': propdef.name,
982 'res_id': obj._name+','+str(id),
990 def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
991 properties = obj.pool.get('ir.property')
992 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
993 domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in ids])]
994 nids = properties.search(cr, uid, domain, context=context)
995 default_val,replaces = self._get_defaults(obj, cr, uid, prop_name, context)
999 res[id] = default_val.copy()
1001 brs = properties.browse(cr, uid, nids, context=context)
1003 value = properties.get_by_record(cr, uid, prop, context=context)
1004 res[prop.res_id.id][prop.fields_id.name] = value or False
1005 if value and (prop.type == 'many2one'):
1006 replaces.setdefault(value._name, {})
1007 replaces[value._name][value.id] = True
1009 for rep in replaces:
1010 replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
1012 for prop in prop_name:
1014 if res[id][prop] and hasattr(res[id][prop], '_name'):
1015 res[id][prop] = (res[id][prop].id , replaces[res[id][prop]._name].get(res[id][prop].id, False))
1020 def _field_get(self, cr, uid, model_name, prop):
1021 if not self.field_id.get(cr.dbname):
1022 cr.execute('SELECT id \
1023 FROM ir_model_fields \
1024 WHERE name=%s AND model=%s', (prop, model_name))
1026 self.field_id[cr.dbname] = res and res[0]
1027 return self.field_id[cr.dbname]
1029 def __init__(self, obj_prop, **args):
1030 # TODO remove obj_prop parameter (use many2one type)
1032 function.__init__(self, self._fnct_read, False, self._fnct_write,
1033 obj_prop, multi='properties', **args)
1039 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: