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
- Účetnictví
- Sklad
- PoS
- Project
- MRP
This question has been flagged
952
Zobrazení
Enjoying the discussion? Don't just read, join in!
Create an account today to enjoy exclusive features and engage with our awesome community!
Přihlásit se| Related Posts | Odpovědi | Zobrazení | Aktivita | |
|---|---|---|---|---|
|
|
2
čvc 24
|
2949 | ||
|
|
2
zář 25
|
1471 | ||
|
|
2
lis 24
|
3515 | ||
|
|
0
srp 24
|
1778 | ||
|
|
1
čvc 24
|
1959 |
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)