odoo中瞬态模型(TransientModel)数据何时清除?

admin 2020-7-10 13963

按官方文档说明,odoo中的瞬态模型中的数据会在某一时刻自动清除:

Model super-class for transient records, meant to be temporarily persistent, and regularly vacuum-cleaned.

至于什么时候执行vacuum 动作,官方文档没有明确说明。

其实这个清理时间是在定时任务中指定的"Setting-->Technical-->Automation-->Scheduled Actions"中,“Base: Auto-vacuum internal data”这个定时任务:


根据这里面的python code,我们进一步确定代码:

class AutoVacuum(models.AbstractModel):
    """ Expose the vacuum method to the cron jobs mechanism. """
    _name = 'ir.autovacuum'
    _description = 'Automatic Vacuum'
    
    @api.model
    def _gc_transient_models(self):
        for mname in self.env:
            model = self.env[mname]
            if model.is_transient():
                try:
                    with self._cr.savepoint():
                        model._transient_vacuum(force=True)
                except Exception as e:
                    _logger.warning("Failed to clean transient model %s\n%s", model, str(e))
                    
    @api.model
    def _gc_user_logs(self):
        self._cr.execute("""
            DELETE FROM res_users_log log1 WHERE EXISTS (
                SELECT 1 FROM res_users_log log2
                WHERE log1.create_uid = log2.create_uid
                AND log1.create_date < log2.create_date
            )
        """)
        _logger.info("GC'd %d user log entries", self._cr.rowcount)
        
    @api.model
    def power_on(self, *args, **kwargs):
        if not self.env.is_admin():
            raise AccessDenied()
        self.env['ir.attachment']._file_gc()
        self._gc_transient_models()
        self._gc_user_logs()
        return True

其中:power_on 是定时任务要执行的函数,里面的 “_gc_transient_models”是清理瞬态模型数据的函数。

扩展:如果我们需要自动清理自己的某个模型数据,可以通过继承“ir.autovacuum”,重写power_on函数,来达到清理自定义模型的目的。



最新回复 (0)
返回