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