There's more...

It is also possible to have some computed and related fields on such models. The only restriction is that the fields cannot be stored (and therefore you cannot use them to group records or to search). However, in the preceding example, we could have made the editor of the book available by adding a column, defined as follows:

publisher_id = fields.Many2one('res.partner', related='book_id.publisher_id', readonly=True)

If you need to group by publisher, then you need to store the field by adding it in the view definition rather than using a related field.

Computed fields are still very useful to have. For instance, in the preceding view, we are expanding the many-to-many relation between books and authors. This means that if you group by book_id and look at the number of loans, a book with two authors will seem to be borrowed twice as much as if it had just one author. If you want to know how many times a book was borrowed and don't wish to write SQL to add a column for this, in the view, you can have a computed field (although to be completely fair, in this specific example, it is much easier to have this in the SQL view):

borrow_count = fields.Integer('Borrow count', compute='_get_borrow_count')
@api.depends('book_id')
def _get_borrow_count(self):
if not self:
return
book_ids = self.mapped('book_id').ids
query = '''SELECT book_id, count(id)
FROM library_book_loan
WHERE book_id in %s GROUP BY book_id'''

self.env.cr.execute(query, (tuple(book_ids),))
counts = dict(self.env.cr.fetchall())
for rec in self:
rec.borrow_count = counts[rec.book_id]

 

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

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