How can you override the create and write methods in a custom Odoo model to automatically log changes in a separate audit model, while avoiding infinite recursion and ensuring transactional integrity?
Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:
- CRM
- e-Commerce
- Comptabilitat
- Inventari
- PoS
- Project
- MRP
This question has been flagged
915
Vistes
Enjoying the discussion? Don't just read, join in!
Create an account today to enjoy exclusive features and engage with our awesome community!
Registrar-se| Related Posts | Respostes | Vistes | Activitat | |
|---|---|---|---|---|
|
|
2
de jul. 24
|
2931 | ||
|
|
2
de set. 25
|
1459 | ||
|
|
2
de nov. 24
|
3469 | ||
|
|
0
d’ag. 24
|
1759 | ||
|
|
1
de jul. 24
|
1926 |
Hello, Here is an example :
my.model — the business model
from odoo import models, fields, api, _
from datetime import datetime
class MyModel(models.Model):
_name = 'my.model'
_description = 'Tracked Business Model'
name = fields.Char()
value = fields.Float()
my.model.audit — the audit trail model
class MyModelAudit(models.Model):
_name = 'my.model.audit'
_description = 'Audit Trail for MyModel'
model_id = fields.Many2one('my.model', string="Target Record")
change_type = fields.Selection([('create', 'Create'), ('write', 'Write')])
field_name = fields.Char()
old_value = fields.Char()
new_value = fields.Char()
changed_on = fields.Datetime(default=lambda self: fields.Datetime.now())
Override of create and write
class MyModel(models.Model):
_inherit = 'my.model'
@api.model
def create(self, vals):
record = super(MyModel, self).create(vals)
for field, value in vals.items():
self.env['my.model.audit'].create({
'model_id': record.id,
'change_type': 'create',
'field_name': field,
'old_value': '',
'new_value': str(value),
})
return record
def write(self, vals):
for record in self:
for field, new_value in vals.items():
old_value = record[field]
if old_value != new_value:
self.env['my.model.audit'].create({
'model_id': record.id,
'change_type': 'write',
'field_name': field,
'old_value': str(old_value),
'new_value': str(new_value),
})
return super(MyModel, self).write(vals)