From 3d1e4abc0b08a22196b63e7ed2a02fcf4080a23e Mon Sep 17 00:00:00 2001 From: "Laurent Mignon (ACSONE)" Date: Wed, 14 Oct 2020 08:21:13 +0200 Subject: [PATCH] [IMP] base_jsonify: Allow to export many2one and referene field as simple field Before this change, the result of the export of a relational field was always a dict or a list of dict. ex: publication_language_id/name publication_language_id/name:lang will output: { ... "publication_language_id" : { "lang": "French" } ... } After this change it's now possible to define simple exporter for relational fields where the value into the result will be the display_name or a list of display_name of the related records. ex: publication_language_id publication_language_id:lang will output: { "lang": "French" } (Cherry-pick of 652c0167a after this commit was dropped by #1894's refactoring) (+ test so that it cannot be forgotten again) --- base_jsonify/models/models.py | 4 ++++ base_jsonify/tests/test_get_parser.py | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/base_jsonify/models/models.py b/base_jsonify/models/models.py index b04f566d8..22bfa6ab8 100644 --- a/base_jsonify/models/models.py +++ b/base_jsonify/models/models.py @@ -48,6 +48,10 @@ class Base(models.AbstractModel): # This call also add the tzinfo into the datetime object value = fields.Datetime.context_timestamp(self, value) value = value.isoformat() + elif field.type in ("many2one", "reference"): + value = value.display_name if value else None + elif field.type in ("one2many", "many2many"): + value = [v.display_name for v in value] return value @api.model diff --git a/base_jsonify/tests/test_get_parser.py b/base_jsonify/tests/test_get_parser.py index 49d767910..43475e11e 100644 --- a/base_jsonify/tests/test_get_parser.py +++ b/base_jsonify/tests/test_get_parser.py @@ -283,6 +283,33 @@ class TestParser(SavepointCase): json = self.category.jsonify(export.get_json_parser())[0] self.assertEqual(json, {"name": "yeah!"}) + def test_export_relational_display_names(self): + """If we export a relational, we get its display_name in the json.""" + parser = [ + "state_id", + "country_id", + "category_id", + "user_ids", + ] + expected_json = { + "state_id": None, + "country_id": "France", + "category_id": ["Inovator"], + "user_ids": [], + } + + json_partner = self.partner.jsonify(parser, one=True) + + self.assertDictEqual(json_partner, expected_json) + + def test_export_reference_display_names(self): + """Reference work the same as relational""" + menu = self.env.ref("base.menu_action_res_users") + + json_menu = menu.jsonify(["action"], one=True) + + self.assertDictEqual(json_menu, {"action": "Users"}) + def test_bad_parsers(self): bad_field_name = ["Name"] with self.assertRaises(KeyError):