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.

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