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
39 from psycopg2 import Binary
41 import openerp.netsvc as netsvc
42 import openerp.tools as tools
43 from openerp.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=None, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
71 self.states = states or {}
73 self.readonly = readonly
74 self.required = required
76 self.help = args.get('help', '')
77 self.priority = priority
78 self.change_default = change_default
79 self.ondelete = ondelete
80 self.translate = translate
82 self._context = context
87 self.selectable = True
88 self.group_operator = args.get('group_operator', False)
91 setattr(self, a, args[a])
96 def set(self, cr, obj, id, name, value, user=None, context=None):
97 cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
99 def set_memory(self, cr, obj, id, name, value, user=None, context=None):
100 raise Exception(_('Not implemented set_memory method !'))
102 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
103 raise Exception(_('Not implemented get_memory method !'))
105 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
106 raise Exception(_('undefined get method !'))
108 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
109 ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
110 res = obj.read(cr, uid, ids, [name], context=context)
111 return [x[name] for x in res]
113 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
114 raise Exception(_('Not implemented search_memory method !'))
117 # ---------------------------------------------------------
119 # ---------------------------------------------------------
120 class boolean(_column):
123 _symbol_f = lambda x: x and 'True' or 'False'
124 _symbol_set = (_symbol_c, _symbol_f)
126 class integer(_column):
129 _symbol_f = lambda x: int(x or 0)
130 _symbol_set = (_symbol_c, _symbol_f)
131 _symbol_get = lambda self,x: x or 0
133 class integer_big(_column):
134 _type = 'integer_big'
135 # do not reference the _symbol_* of integer class, as that would possibly
136 # unbind the lambda functions
138 _symbol_f = lambda x: int(x or 0)
139 _symbol_set = (_symbol_c, _symbol_f)
140 _symbol_get = lambda self,x: x or 0
142 class reference(_column):
144 def __init__(self, string, selection, size, **args):
145 _column.__init__(self, string=string, size=size, selection=selection, **args)
151 def __init__(self, string, size, **args):
152 _column.__init__(self, string=string, size=size, **args)
153 self._symbol_set = (self._symbol_c, self._symbol_set_char)
155 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
156 def _symbol_set_char(self, symb):
158 # * we need to remove the "symb==False" from the next line BUT
159 # for now too many things rely on this broken behavior
160 # * the symb==None test should be common to all data types
161 if symb == None or symb == False:
164 # we need to convert the string to a unicode object to be able
165 # to evaluate its length (and possibly truncate it) reliably
166 u_symb = tools.ustr(symb)
168 return u_symb[:self.size].encode('utf8')
176 class float(_column):
179 _symbol_f = lambda x: __builtin__.float(x or 0.0)
180 _symbol_set = (_symbol_c, _symbol_f)
181 _symbol_get = lambda self,x: x or 0.0
183 def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
184 _column.__init__(self, string=string, **args)
186 self.digits_compute = digits_compute
189 def digits_change(self, cr):
190 if self.digits_compute:
191 t = self.digits_compute(cr)
192 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
199 """ Returns the current date in a format fit for being a
200 default value to a ``date`` field.
202 This method should be provided as is to the _defaults dict, it
203 should not be called.
205 return DT.date.today().strftime(
206 tools.DEFAULT_SERVER_DATE_FORMAT)
208 class datetime(_column):
212 """ Returns the current datetime in a format fit for being a
213 default value to a ``datetime`` field.
215 This method should be provided as is to the _defaults dict, it
216 should not be called.
218 return DT.datetime.now().strftime(
219 tools.DEFAULT_SERVER_DATETIME_FORMAT)
225 """ Returns the current time in a format fit for being a
226 default value to a ``time`` field.
228 This method should be proivided as is to the _defaults dict,
229 it should not be called.
231 return DT.datetime.now().strftime(
232 tools.DEFAULT_SERVER_TIME_FORMAT)
234 class binary(_column):
237 _symbol_f = lambda symb: symb and Binary(symb) or None
238 _symbol_set = (_symbol_c, _symbol_f)
239 _symbol_get = lambda self, x: x and str(x)
241 _classic_read = False
244 def __init__(self, string='unknown', filters=None, **args):
245 _column.__init__(self, string=string, **args)
246 self.filters = filters
248 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
261 # If client is requesting only the size of the field, we return it instead
262 # of the content. Presumably a separate request will be done to read the actual
263 # content if it's needed at some point.
264 # TODO: after 6.0 we should consider returning a dict with size and content instead of
265 # having an implicit convention for the value
266 if val and context.get('bin_size_%s' % name, context.get('bin_size')):
267 res[i] = tools.human_size(long(val))
275 class selection(_column):
278 def __init__(self, selection, string='unknown', **args):
279 _column.__init__(self, string=string, **args)
280 self.selection = selection
282 # ---------------------------------------------------------
284 # ---------------------------------------------------------
287 # Values: (0, 0, { fields }) create
288 # (1, ID, { fields }) update
289 # (2, ID) remove (delete)
290 # (3, ID) unlink one (target id or target of relation)
292 # (5) unlink all (only valid for one2many)
294 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
295 class one2one(_column):
296 _classic_read = False
297 _classic_write = True
300 def __init__(self, obj, string='unknown', **args):
301 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
302 _column.__init__(self, string=string, **args)
305 def set(self, cr, obj_src, id, field, act, user=None, context=None):
308 obj = obj_src.pool.get(self._obj)
309 self._table = obj_src.pool.get(self._obj)._table
311 id_new = obj.create(cr, user, act[1])
312 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
314 cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
315 id = cr.fetchone()[0]
316 obj.write(cr, user, [id], act[1], context=context)
318 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
319 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
322 class many2one(_column):
323 _classic_read = False
324 _classic_write = True
327 _symbol_f = lambda x: x or None
328 _symbol_set = (_symbol_c, _symbol_f)
330 def __init__(self, obj, string='unknown', **args):
331 _column.__init__(self, string=string, **args)
334 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
335 obj.datas.setdefault(id, {})
336 obj.datas[id][field] = values
338 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
341 result[id] = obj.datas[id].get(name, False)
343 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
344 # we use uid=1 because the visibility of a many2one field value (just id and name)
345 # must be the access right of the parent form and not the linked object itself.
346 obj = obj.pool.get(self._obj)
347 records = dict(obj.name_get(cr, 1,
348 list(set([x for x in result.values() if x and isinstance(x, (int,long))])),
351 if result[id] in records:
352 result[id] = (result[id], records[result[id]])
358 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
366 res[r['id']] = r[name]
368 res.setdefault(id, '')
369 obj = obj.pool.get(self._obj)
371 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
372 # we use uid=1 because the visibility of a many2one field value (just id and name)
373 # must be the access right of the parent form and not the linked object itself.
374 records = dict(obj.name_get(cr, 1,
375 list(set([x for x in res.values() if isinstance(x, (int,long))])),
378 if res[id] in records:
379 res[id] = (res[id], records[res[id]])
384 def set(self, cr, obj_src, id, field, values, user=None, context=None):
387 obj = obj_src.pool.get(self._obj)
388 self._table = obj_src.pool.get(self._obj)._table
389 if type(values) == type([]):
392 id_new = obj.create(cr, act[2])
393 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
395 obj.write(cr, [act[1]], act[2], context=context)
397 cr.execute('delete from '+self._table+' where id=%s', (act[1],))
398 elif act[0] == 3 or act[0] == 5:
399 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
401 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
404 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
406 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
408 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
409 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
412 class one2many(_column):
413 _classic_read = False
414 _classic_write = False
418 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
419 _column.__init__(self, string=string, **args)
421 self._fields_id = fields_id
423 #one2many can't be used as condition for defaults
424 assert(self.change_default != True)
426 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
430 context = context.copy()
431 context.update(self._context)
437 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
438 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
439 if r[self._fields_id] in res:
440 res[r[self._fields_id]].append(r['id'])
443 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
447 context = context.copy()
448 context.update(self._context)
451 obj = obj.pool.get(self._obj)
454 act[2][self._fields_id] = id
455 obj.create(cr, user, act[2], context=context)
457 obj.write(cr, user, [act[1]], act[2], context=context)
459 obj.unlink(cr, user, [act[1]], context=context)
461 obj.datas[act[1]][self._fields_id] = False
463 obj.datas[act[1]][self._fields_id] = id
465 for o in obj.datas.values():
466 if o[self._fields_id] == id:
467 o[self._fields_id] = False
469 for id2 in (act[2] or []):
470 obj.datas[id2][self._fields_id] = id
472 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
473 raise _('Not Implemented')
475 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
479 context = context.copy()
480 context.update(self._context)
488 ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
489 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
490 if r[self._fields_id] in res:
491 res[r[self._fields_id]].append(r['id'])
494 def set(self, cr, obj, id, field, values, user=None, context=None):
499 context = context.copy()
500 context.update(self._context)
501 context['no_store_function'] = True
504 _table = obj.pool.get(self._obj)._table
505 obj = obj.pool.get(self._obj)
508 act[2][self._fields_id] = id
509 id_new = obj.create(cr, user, act[2], context=context)
510 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
512 obj.write(cr, user, [act[1]], act[2], context=context)
514 obj.unlink(cr, user, [act[1]], context=context)
516 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
518 # Must use write() to recompute parent_store structure if needed
519 obj.write(cr, user, [act[1]], {self._fields_id:id}, context=context or {})
521 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
523 # Must use write() to recompute parent_store structure if needed
524 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
526 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
527 ids3 = map(lambda x:x[0], cr.fetchall())
528 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
531 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
532 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
536 # Values: (0, 0, { fields }) create
537 # (1, ID, { fields }) update (write fields to ID)
538 # (2, ID) remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
539 # (3, ID) unlink (delete the relationship between the two objects but does not delete ID)
540 # (4, ID) link (add a relationship)
542 # (6, ?, ids) set a list of links
544 class many2many(_column):
545 _classic_read = False
546 _classic_write = False
549 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
550 _column.__init__(self, string=string, **args)
553 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
554 'You used %s, which is not a valid SQL table name.')% (string,rel))
560 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
571 warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.",
572 DeprecationWarning, stacklevel=2)
573 obj = obj.pool.get(self._obj)
575 # static domains are lists, and are evaluated both here and on client-side, while string
576 # domains supposed by dynamic and evaluated on client-side only (thus ignored here)
577 # FIXME: make this distinction explicit in API!
578 domain = isinstance(self._domain, list) and self._domain or []
580 wquery = obj._where_calc(cr, user, domain, context=context)
581 obj._apply_ir_rules(cr, user, wquery, 'read', context=context)
582 from_c, where_c, where_params = wquery.get_sql()
584 where_c = ' AND ' + where_c
586 if offset or self._limit:
587 order_by = ' ORDER BY "%s".%s' %(obj._table, obj._order.split(',')[0])
592 if self._limit is not None:
593 limit_str = ' LIMIT %d' % self._limit
595 query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
596 FROM %(rel)s, %(from_c)s \
597 WHERE %(rel)s.%(id1)s IN %%s \
598 AND %(rel)s.%(id2)s = %(tbl)s.id \
610 'order_by': order_by,
613 cr.execute(query, [tuple(ids),] + where_params)
614 for r in cr.fetchall():
615 res[r[1]].append(r[0])
618 def set(self, cr, obj, id, name, values, user=None, context=None):
623 obj = obj.pool.get(self._obj)
625 if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
628 idnew = obj.create(cr, user, act[2])
629 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
631 obj.write(cr, user, [act[1]], act[2], context=context)
633 obj.unlink(cr, user, [act[1]], context=context)
635 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
637 # following queries are in the same transaction - so should be relatively safe
638 cr.execute('SELECT 1 FROM '+self._rel+' WHERE '+self._id1+' = %s and '+self._id2+' = %s', (id, act[1]))
639 if not cr.fetchone():
640 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
642 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
645 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
647 d1 = ' and ' + ' and '.join(d1)
650 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)
652 for act_nbr in act[2]:
653 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
656 # TODO: use a name_search
658 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
659 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
661 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
664 result[id] = obj.datas[id].get(name, [])
667 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
671 # TODO: use constants instead of these magic numbers
673 raise _('Not Implemented')
675 raise _('Not Implemented')
677 raise _('Not Implemented')
679 raise _('Not Implemented')
681 raise _('Not Implemented')
683 raise _('Not Implemented')
685 obj.datas[id][name] = act[2]
688 def get_nice_size(a):
691 if isinstance(y, (int,long)):
695 return (x, tools.human_size(size))
697 def sanitize_binary_value(dict_item):
698 # binary fields should be 7-bit ASCII base64-encoded data,
699 # but we do additional sanity checks to make sure the values
700 # are not something else that won't pass via xmlrpc
701 if isinstance(dict_item, (xmlrpclib.Binary, tuple, dict)):
702 # these builtin types are meant to pass untouched
705 # For all other cases, handle the value as a binary string:
706 # it could be a 7-bit ASCII string (e.g base64 data), but also
707 # any 8-bit content from files, with byte values that cannot
708 # be passed inside XML!
710 # - http://bugs.python.org/issue10066
711 # - http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char
713 # One solution is to convert the byte-string to unicode,
714 # so it gets serialized as utf-8 encoded data (always valid XML)
715 # If invalid XML byte values were present, tools.ustr() uses
716 # the Latin-1 codec as fallback, which converts any 8-bit
717 # byte value, resulting in valid utf-8-encoded bytes
719 # >>> unicode('\xe1','latin1').encode('utf8') == '\xc3\xa1'
720 # Note: when this happens, decoding on the other endpoint
721 # is not likely to produce the expected output, but this is
722 # just a safety mechanism (in these cases base64 data or
723 # xmlrpc.Binary values should be used instead)
724 return tools.ustr(dict_item)
727 # ---------------------------------------------------------
729 # ---------------------------------------------------------
730 class function(_column):
731 _classic_read = False
732 _classic_write = False
738 # multi: compute several fields in one call
740 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):
741 _column.__init__(self, **args)
743 self._method = method
745 self._fnct_inv = fnct_inv
748 if 'relation' in args:
749 self._obj = args['relation']
751 self.digits = args.get('digits', (16,2))
752 self.digits_compute = args.get('digits_compute', None)
754 self._fnct_inv_arg = fnct_inv_arg
758 self._fnct_search = fnct_search
761 if not fnct_search and not store:
762 self.selectable = False
765 if self._type != 'many2one':
766 # m2o fields need to return tuples with name_get, not just foreign keys
767 self._classic_read = True
768 self._classic_write = True
770 self._symbol_get=lambda x:x and str(x)
773 self._symbol_c = float._symbol_c
774 self._symbol_f = float._symbol_f
775 self._symbol_set = float._symbol_set
777 if type == 'boolean':
778 self._symbol_c = boolean._symbol_c
779 self._symbol_f = boolean._symbol_f
780 self._symbol_set = boolean._symbol_set
782 if type in ['integer','integer_big']:
783 self._symbol_c = integer._symbol_c
784 self._symbol_f = integer._symbol_f
785 self._symbol_set = integer._symbol_set
787 def digits_change(self, cr):
788 if self.digits_compute:
789 t = self.digits_compute(cr)
790 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
794 def search(self, cr, uid, obj, name, args, context=None):
795 if not self._fnct_search:
796 #CHECKME: should raise an exception
798 return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
800 def postprocess(self, cr, user, obj, type, value=None, context=None):
805 if context.get('bin_size', False):
806 # client requests only the size of binary fields
807 result = get_nice_size(value)
809 result = sanitize_binary_value(value)
811 if type == "integer":
812 result = tools.ustr(value)
815 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
822 result = self._fnct(obj, cr, user, ids, name, self._arg, context)
824 result = self._fnct(cr, obj._table, ids, name, self._arg, context)
826 if self._multi and result.get(id, {}):
827 for field, value in result[id].iteritems():
829 result[id][field] = self.postprocess(cr, user, obj, obj._columns[field]._type, value)
830 elif result.get(id, False) and result[id]:
831 result[id] = self.postprocess(cr, user, obj, self._type, result[id])
836 def set(self, cr, obj, id, name, value, user=None, context=None):
840 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
843 # ---------------------------------------------------------
845 # ---------------------------------------------------------
847 class related(function):
849 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
850 self._field_get2(cr, uid, obj, context)
854 if type(sarg) in [type([]), type( (1,) )]:
855 where = [(self._arg[i], 'in', sarg)]
857 where = [(self._arg[i], '=', sarg)]
859 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
861 sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
863 return [(self._arg[0], 'in', sarg)]
865 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
866 self._field_get2(cr, uid, obj, context=context)
867 if type(ids) != type([]):
869 objlst = obj.browse(cr, uid, ids)
873 for i in range(len(self.arg)):
875 field_detail = self._relations[i]
876 if not t_data[self.arg[i]]:
877 if self._type not in ('one2many', 'many2many'):
880 elif field_detail['type'] in ('one2many', 'many2many'):
881 if self._type != "many2one":
883 t_data = t_data[self.arg[i]][0]
888 t_data = t_data[self.arg[i]]
890 model = obj.pool.get(self._relations[-1]['object'])
891 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
893 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
894 self._field_get2(cr, uid, obj, context)
895 if not ids: return {}
897 if self._type in ('one2many', 'many2many'):
898 res = dict([(i, []) for i in ids])
900 res = {}.fromkeys(ids, False)
902 objlst = obj.browse(cr, 1, ids, context=context)
908 for i in range(len(self.arg)):
909 field_detail = self._relations[i]
910 relation = field_detail['object']
912 if not t_data[self.arg[i]]:
918 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
919 t_data = t_data[self.arg[i]][0]
921 t_data = t_data[self.arg[i]]
922 if type(t_data) == type(objlst[0]):
923 res[data.id] = t_data.id
925 res[data.id] = t_data
926 if self._type=='many2one':
927 ids = filter(None, res.values())
929 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
932 res[r] = (res[r], ng[res[r]])
933 elif self._type in ('one2many', 'many2many'):
936 res[r] = [x.id for x in res[r]]
939 def __init__(self, *arg, **args):
942 super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
943 if self.store is True:
944 # TODO: improve here to change self.store = {...} according to related objects
947 def _field_get2(self, cr, uid, obj, context=None):
951 for i in range(len(self._arg)):
952 f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
953 self._relations.append({
958 if f.get('relation',False):
959 obj_name = f['relation']
960 self._relations[-1]['relation'] = f['relation']
962 # ---------------------------------------------------------
964 # ---------------------------------------------------------
966 class dummy(function):
967 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
970 def _fnct_write(self, obj, cr, uid, ids, field_name, values, args, context=None):
973 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
976 def __init__(self, *arg, **args):
979 super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
981 # ---------------------------------------------------------
983 # ---------------------------------------------------------
984 class serialized(_column):
985 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
986 self._serialize_func = serialize_func
987 self._deserialize_func = deserialize_func
989 self._symbol_set = (self._symbol_c, self._serialize_func)
990 self._symbol_get = self._deserialize_func
991 super(serialized, self).__init__(string=string, **args)
994 # TODO: review completly this class for speed improvement
995 class property(function):
997 def _get_default(self, obj, cr, uid, prop_name, context=None):
998 return self._get_defaults(obj, cr, uid, [prop_name], context=None)[0][prop_name]
1000 def _get_defaults(self, obj, cr, uid, prop_name, context=None):
1001 prop = obj.pool.get('ir.property')
1002 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
1003 ids = prop.search(cr, uid, domain, context=context)
1005 default_value = {}.fromkeys(prop_name, False)
1006 for prop_rec in prop.browse(cr, uid, ids, context=context):
1007 if default_value.get(prop_rec.fields_id.name, False):
1009 value = prop.get_by_record(cr, uid, prop_rec, context=context) or False
1010 default_value[prop_rec.fields_id.name] = value
1011 if value and (prop_rec.type == 'many2one'):
1012 replaces.setdefault(value._name, {})
1013 replaces[value._name][value.id] = True
1014 return default_value, replaces
1016 def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
1017 prop = obj.pool.get('ir.property')
1018 vids = [obj._name + ',' + str(oid) for oid in ids]
1020 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
1021 #domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
1023 domain = [('res_id', 'in', vids)] + domain
1024 return prop.search(cr, uid, domain, context=context)
1026 # TODO: to rewrite more clean
1027 def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
1031 nids = self._get_by_id(obj, cr, uid, [prop_name], [id], context)
1033 cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
1035 default_val = self._get_default(obj, cr, uid, prop_name, context)
1037 if id_val is not default_val:
1038 def_id = self._field_get(cr, uid, obj._name, prop_name)
1039 company = obj.pool.get('res.company')
1040 cid = company._company_default_get(cr, uid, obj._name, def_id,
1042 propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
1044 prop = obj.pool.get('ir.property')
1045 return prop.create(cr, uid, {
1046 'name': propdef.name,
1048 'res_id': obj._name+','+str(id),
1050 'fields_id': def_id,
1056 def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
1057 properties = obj.pool.get('ir.property')
1058 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
1059 domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in ids])]
1060 nids = properties.search(cr, uid, domain, context=context)
1061 default_val,replaces = self._get_defaults(obj, cr, uid, prop_name, context)
1065 res[id] = default_val.copy()
1067 brs = properties.browse(cr, uid, nids, context=context)
1069 value = properties.get_by_record(cr, uid, prop, context=context)
1070 res[prop.res_id.id][prop.fields_id.name] = value or False
1071 if value and (prop.type == 'many2one'):
1072 record_exists = obj.pool.get(value._name).exists(cr, uid, value.id)
1074 replaces.setdefault(value._name, {})
1075 replaces[value._name][value.id] = True
1077 res[prop.res_id.id][prop.fields_id.name] = False
1079 for rep in replaces:
1080 nids = obj.pool.get(rep).search(cr, uid, [('id','in',replaces[rep].keys())], context=context)
1081 replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, nids, context=context))
1083 for prop in prop_name:
1085 if res[id][prop] and hasattr(res[id][prop], '_name'):
1086 res[id][prop] = (res[id][prop].id , replaces[res[id][prop]._name].get(res[id][prop].id, False))
1091 def _field_get(self, cr, uid, model_name, prop):
1092 if not self.field_id.get(cr.dbname):
1093 cr.execute('SELECT id \
1094 FROM ir_model_fields \
1095 WHERE name=%s AND model=%s', (prop, model_name))
1097 self.field_id[cr.dbname] = res and res[0]
1098 return self.field_id[cr.dbname]
1100 def __init__(self, obj_prop, **args):
1101 # TODO remove obj_prop parameter (use many2one type)
1103 function.__init__(self, self._fnct_read, False, self._fnct_write,
1104 obj_prop, multi='properties', **args)
1110 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: