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.

75 lines
2.6 KiB

  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 odoo import api, models
  7. from odoo.exceptions import UserError
  8. from odoo.tools.translate import _
  9. class Base(models.AbstractModel):
  10. _inherit = 'base'
  11. @api.model
  12. def __parse_field(self, parser_field):
  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 parser given
  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 consitent 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