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.

78 lines
2.5 KiB

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