To get the information about the average number of days a user keeps a particular book, you need to perform the following steps:
- Add the average_book_occupation() method to library.book:
def average_book_occupation(self):
...
- In the method, write the following SQL query:
sql_query = """
SELECT
lb.name,
avg((EXTRACT(epoch from age(return_date, rent_date)) / 86400))::int
FROM
library_book_rent AS lbr
JOIN
library_book as lb ON lb.id = lbr.book_id
WHERE lbr.state = 'returned'
GROUP BY lb.name;"""
- Execute the query:
self.env.cr.execute(sql_query)
- Fetch the result and log it:
result = self.env.cr.fetchall()
logger.info("Average book occupation: %s", result)
- Add a button in the form view of the library.book mode to trigger our method:
<button name="average_book_occupation" string="Log Average Occ." type="object" />
Don't forgot to import logging in this file. Then, restart and update the my_library module.