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.

76 lines
2.4 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. empty_value = {
  39. 'char': '',
  40. 'int': 0,
  41. 'float': 0,
  42. }
  43. for rec in self:
  44. res = {}
  45. for field in parser:
  46. field_name, json_key, subparser = __parse_field(field)
  47. field_type = rec._fields[field_name].type
  48. if subparser:
  49. if field_type in ('one2many', 'many2many'):
  50. res[json_key] = rec[field_name].jsonify(subparser)
  51. elif field_type in ('many2one', 'reference'):
  52. if rec[field_name]:
  53. res[json_key] = rec[field_name].jsonify(subparser)[0]
  54. else:
  55. res[json_key] = None
  56. else:
  57. raise UserError(_('Wrong parser configuration'))
  58. else:
  59. res[json_key] = rec[field_name]
  60. if not res[json_key] and field_type in empty_value:
  61. res[json_key] = empty_value[field_type]
  62. result.append(res)
  63. return result
  64. models.Model.jsonify = jsonify