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.

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