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.

77 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. """
  13. Deducts how to handle a field from its parser
  14. """
  15. field_name = parser_field
  16. subparser = None
  17. if isinstance(parser_field, tuple):
  18. field_name, subparser = parser_field
  19. json_key = field_name
  20. if ':' in field_name:
  21. field_name, json_key = field_name.split(':')
  22. return field_name, json_key, subparser
  23. @api.multi
  24. def jsonify(self, parser):
  25. """ Convert the record according to the parser given
  26. Example of parser:
  27. parser = [
  28. 'name',
  29. 'number',
  30. 'create_date',
  31. ('partner_id', ['id', 'display_name', 'ref'])
  32. ('line_id', ['id', ('product_id', ['name']), 'price_unit'])
  33. ]
  34. In order to be consistent with the odoo api the jsonify method always
  35. return a list of object even if there is only one element in input
  36. By default the key into the json is the name of the field extracted
  37. from the model. If you need to specify an alternate name to use as
  38. key, you can define your mapping as follow into the parser definition:
  39. parser = [
  40. 'field_name:json_key'
  41. ]
  42. """
  43. result = []
  44. for rec in self:
  45. res = {}
  46. for field in parser:
  47. field_name, json_key, subparser = self.__parse_field(field)
  48. field_type = rec._fields[field_name].type
  49. if subparser:
  50. if field_type in ('one2many', 'many2many'):
  51. res[json_key] = rec[field_name].jsonify(subparser)
  52. elif field_type in ('many2one', 'reference'):
  53. if rec[field_name]:
  54. res[json_key] =\
  55. rec[field_name].jsonify(subparser)[0]
  56. else:
  57. res[json_key] = None
  58. else:
  59. raise UserError(_('Wrong parser configuration'))
  60. else:
  61. value = rec[field_name]
  62. if value is False and field_type != 'boolean':
  63. value = None
  64. res[json_key] = value
  65. result.append(res)
  66. return result