I'd like to keep track on what field has changed on any model (i.e. audit at model level since it's more atomic, not at admin/form-level like what django and django-reversion can already do). I'm able to do that for any field using pre/post save/delete signals. However, I have a problem of doing that on an m2m field.
For the code sample below, i define 'custom_groups' m2m field in user change form since it's a reverse relation. When user saves the form on admin interface for example, I'd like to log if there's a change in 'custom_groups' field.
Model:
from django.contrib.auth.models import User
class CustomGroup(models.Model):
users = models.ManyToManyField(User, related_name='custom_groups')
ModelForm:
class CustomUserChangeForm(UserChangeForm):
custom_groups = forms.ModelMultipleChoiceField(required=False, queryset=CustomGroup.objects.all())
The problem with using m2m_changed signal is that i can't check what has actually changed for the case where the m2m field is updated using assignment operator:
user.custom_groups = self.cleaned_data['custom_groups']
This is because internally django will perform a clear() on *custom_groups*, before manually adding all objects. This will execute pre/post-clear and then pre/post save on the m2m field.
Am I doing all this the wrong way? Is there a simpler method that can actually work?
Thanks!