[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:

<record id="ir_exp_shopinvader_variant_lang" model="ir.exports.line">
  <field name="name">publication_language_id/name</field>
  <field name="alias">publication_language_id/name:lang</field>
  <field name="export_id" ref="shopinvader.ir_exp_shopinvader_variant" />
</record>

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:

<record id="ir_exp_shopinvader_variant_lang" model="ir.exports.line">
  <field name="name">publication_language_id</field>
  <field name="alias">publication_language_id:lang</field>
  <field name="export_id" ref="shopinvader.ir_exp_shopinvader_variant" />
</record>

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)
pull/2418/head
Laurent Mignon (ACSONE) 2020-10-14 08:21:13 +02:00 committed by Sébastien BEAU
parent 4b4d6bae70
commit 3d1e4abc0b
2 changed files with 31 additions and 0 deletions

View File

@ -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

View File

@ -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):