Exposing Related fields stored in other models

When reading data from the server, Odoo clients can only get values for the fields available in the model being queried. Client-side code can't use dot notation to access data in the related tables like server-side code can.

But those fields can be made available there by adding them as related fields. We will do this to make the publisher's city available in the Library Book model.

Getting ready

We will reuse the my_module addon module from Chapter 3, Create Odoo Modules.

How to do it…

Edit the models/library_book.py file to add the new "related" field:

  1. Make sure that we have a field for the book Publisher:
    class LibraryBook(models.Model):
        # ...
        publisher_id = fields.Many2one(
            'res.partner', string='Publisher')
  2. Now, add the related field for the Publisher's city:
    # class LibraryBook(models.Model):
        # ...
        publisher_city = fields.Char(
            'Publisher City',
            related='publisher_id.city')
    

Finally, we need to upgrade the addon module for the new fields to be available in the Model.

How it works…

Related fields are just like regular fields, but they have the additional attribute, related, with a string for the separated chain of fields to traverse.

In our case, we access the Publisher related record through publisher_id, and then read its city field. We can also have longer chains, such as publisher_id.country_id.country_code.

There's more…

Related fields are in fact computed fields. They just provide a convenient shortcut syntax to read field values from related models. As a computed field, this means that the store attribute is also available to them. As a shortcut, they also have all the attributes from the referenced field, such as name, translatable, required, and so on.

Additionally, they support a related_sudo flag similar to compute_sudo; when set to True, the field chain is traversed without checking user access rights.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.240.80