I want to track changes in records of my One2many fields. I've tried the following code:
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
for record in records:
if record.lead_id:
message = f"New Secondary Salesman Added: {record.name}"
record.lead_id.message_post(body=message, **{'body_is_html': True})
return records
def write(self, vals):
# Store original values before the write operation
old_values = {}
for field_name, value in vals.items():
if field_name in self._fields and self._fields[field_name].tracking:
# For basic fields (Char, Float, Integer, etc.), directly store the old value
# For Many2one, you might want to store the display_name or ID
if self._fields[field_name].relational:
old_values[field_name] = self[field_name].display_name if self[field_name] else False
else:
old_values[field_name] = self[field_name]
res = super().write(vals)
for record in self:
if record.lead_id:
body_message = f"<b>Changes to Secondary Salesman info '{record.display_name}':</b><br/>"
has_changes = False
for field_name, new_value in vals.items():
if field_name in record._fields and record._fields[field_name].tracking:
old_value = old_values.get(field_name)
current_value = record[field_name]
# Handle different field types for comparison and display
if record._fields[field_name].relational:
current_display_value = current_value.display_name if current_value else False
if str(old_value) != str(current_display_value): Compare display names or IDs
has_changes = True
field_description = record._fields[field_name].string
body_message += f"<li>{old_value or ''} to {current_display_value or ''} ({field_description})<br/>"
# elif str(old_value) != str(current_value): # For non-relational fields
# has_changes = True
# field_description = record._fields[field_name].string
# body_message += f"<li>{old_value or ''} to {current_value or ''} ({field_description}) <br/>"
# if has_changes:
# record.lead_id.message_post(body=body_message, **{'body_is_html': True})
# return res
# def unlink(self):
# for record in self:
# if record.lead_id:
# message = f"<b>Salesman Deleted:</b> {record.display_name}"
# record.lead_id.message_post(body=message, **{'body_is_html': True})
# return super().unlink()
While this works well for one model, when I add this to multiple models, I get the following error either while creating a new record or updating an existing one.
What is causing the error? OR
How can I add tracking information to my form's chatter?
Odoo v18 Community edition