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.7 KiB

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