How to do it...

We will edit the models/library_book.py code file to add a new field and the methods supporting its logic:

  1. Start by adding the new field to the Library Books model:
class LibraryBook(models.Model): 
    # ... 
    age_days = fields.Float( 
        string='Days Since Release', 
        compute='_compute_age', 
        inverse='_inverse_age', 
        search='_search_age', 
        store=False, 
        compute_sudo=False, 
    ) 
  1. Next, add the method with the value computation logic:
# ... 
from odoo import api  # if not already imported 
from odoo.fields import Date as fDate 
# ... 
class LibraryBook(models.Model): 
    # ... 
    @api.depends('date_release') 
    def _compute_age(self): 
        today = fDate.from_string(fDate.today()) 
        for book in self.filtered('date_release'): 
            delta = (today -
fDate.from_string(book.date_release)) book.age_days = delta.days
  1. To add the method implementing the logic to write on the computed field, use the following code:
from datetime import timedelta
# ... 
class LibraryBook(models.Model): 
    # ... 
    def _inverse_age(self):
today = fDate.from_string(fDate.context_today(self)) for book in self.filtered('date_release'): d = today - timedelta(days=book.age_days) book.date_release = fDate.to_string(d)
  1. To implement the logic allowing you to search on the computed field, use the following code:
# from datetime import timedelta
class LibraryBook(models.Model): 
    # ... 
    def _search_age(self, operator, value): 
        today = fDate.from_string(fDate.context_today(self)) 
        value_days = timedelta(days=value) 
        value_date = fDate.to_string(today - value_days)
# convert the operator:
# book with age > value have a date < value_date
operator_map = {
'>': '<', '>=': '<=',
'<': '>', '<=': '>=',
}
new_op = operator_map.get(operator, operator)
return [('date_release', new_op, value_date)]

An Odoo restart followed by a module upgrade should be needed to correctly activate these new additions.

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

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