ORM cache
Within the Odoo framework, the ORM Cache decorator facilitates the management of in-memory caches. This guide delves into the intricacies of function caching.
The classes associated with this ORM cache are located at /odoo/tools/cache.py. To integrate them into any record, import these classes as needed.
By importing the class from Odoo with the statement from Odoo import tools, you gain access to the ORM cache decorator. Odoo provides various types of in-memory cache decorators, each detailed in the following sections.
ormcache
The ormcache is a straightforward and widely used cache decorator. To employ it, specify the method's dependent argument names. Illustrated below is an example method using the ormcache decorator:
@tools.ormcache('key')
def _check_data(self, key):
# some code
return result
When this method is initially called, it executes and returns the result. Subsequent calls with the same key value retrieve the result from the cache, bypassing the actual execution of the method.
In situations where method results rely on environmental attributes, declare the method accordingly:
@tools.ormcache('self.env.uid', 'key')
def _check_data(self, key):
# some code
return result
This example method saves the cache based on the values of the environment user and mode parameters.
ormcache_context
The ormcache_context functions similarly to ormcache but depends on parameters and values in the context. To utilize this cache decorator, provide a list of parameter names and context keys. For instance, if your method's output relies on the lang and timezone (tz) keys in the context, you can use ormcache_context as follows:
@tools.ormcache_context('name', keys=('tz', 'lang'))
def _check_data(self, key):
# some code
return result
In this example, the cache is contingent on both key arguments and the values of the specified context keys.
Least Recently Used (LRU)
The ORM cache operates as a Least Recently Used (LRU) cache, meaning that infrequently used keys are systematically removed. Misusing ORM caching can be counterproductive. For instance, if method arguments consistently vary, Odoo will repeatedly check the cache before invoking the method for computation. To gain insights into caching operations, send the SIGUSR1 signal to the Odoo process:
kill -SIGUSR1
Replace with the process ID (e.g., 674269). After executing the command, review the ORM cache status in the logs:
kill -SIGUSR1 674269
The cache percentage represents the hit-to-miss ratio, indicating the success rate of finding results in the cache. If the cache hit/miss ratio is notably low, it may be prudent to reconsider incorporating the ORM cache in your method.