You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2016 Akretion (http://www.akretion.com)
  3. # Sébastien BEAU <sebastien.beau@akretion.com>
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. from openerp import api, models
  6. from openerp.exceptions import Warning as UserError
  7. from openerp.tools.translate import _
  8. def __parse_field(parser_field):
  9. field_name = parser_field
  10. subparser = None
  11. if isinstance(parser_field, tuple):
  12. field_name, subparser = parser_field
  13. json_key = field_name
  14. if ':' in field_name:
  15. field_name, json_key = field_name.split(':')
  16. return field_name, json_key, subparser
  17. @api.multi
  18. def jsonify(self, parser):
  19. """ Convert the record according to the parser given
  20. Example of parser:
  21. parser = [
  22. 'name',
  23. 'number',
  24. 'create_date',
  25. ('partner_id', ['id', 'display_name', 'ref'])
  26. ('line_id', ['id', ('product_id', ['name']), 'price_unit'])
  27. ]
  28. In order to be consitent with the odoo api the jsonify method always
  29. return a list of object even if there is only one element in input
  30. By default the key into the json is the name of the field extracted
  31. from the model. If you need to specify an alternate name to use as key, you
  32. can define your mapping as follow into the parser definition:
  33. parser = [
  34. 'field_name:json_key'
  35. ]
  36. """
  37. result = []
  38. for rec in self:
  39. res = {}
  40. for field in parser:
  41. field_name, json_key, subparser = __parse_field(field)
  42. if subparser:
  43. field_type = rec._fields[field_name].type
  44. if field_type in ('one2many', 'many2many'):
  45. res[json_key] = rec[field_name].jsonify(subparser)
  46. elif field_type == 'many2one':
  47. data = rec[field_name].jsonify(subparser)
  48. if data:
  49. res[json_key] = data[0]
  50. else:
  51. res[json_key] = None
  52. else:
  53. raise UserError(_('Wrong parser configuration'))
  54. else:
  55. res[json_key] = rec[field_name]
  56. result.append(res)
  57. return result
  58. models.Model.jsonify = jsonify