Dealing with m2m changes in Django on object save
So I'm building a webhook functionality for a particular Django model, as in I trigger the webhooks for 2 events. One is for creation and one for modification, as in I wanna trigger them everytime an object of that model is created/updated.
So, generally for other models, the pattern I follow is:
class Model1(models.Model):
...
fields
...
def save(self. *args, **kwargs):
self.is_new = self._state.adding
super().save(*args, **kwargs)
self.post_save()
def post_save(self):
if self.is_new:
# Trigger webhook with self object as the payload.
trigger_webhook(self)
Now, with the current model I'm working, the only difference is that it has an m2m field on it, like:
class Model2(models.Model):
...
fields
m2m_field = models.ManyToManyField(
Model3,
through="Model1Model2",
blank=True,
related_name="...",
)
...
Now, for this model, when save() is triggered, the m2m field always comes out empty as apparently it's updated beyond this point and we need the field as part of our payload in the webhook. One of the solutions I tried was use a signal like:
@receiver(m2m_changed, sender=Model1Model2)
def signal_ready(sender, instance, action, **kwargs):
if action not in ("post_add", "post_remove", "post_clear"):
return
trigger_model_webhook(instance)
This did work for the case where the m2m field was changed or added during creation, but the limitation with this approach is that if we create an object where the m2m field wasn't added or changed, the webhook isn't triggered at all while it should.
Are there any other possible approaches to do this where we can maybe add a conditional check to see if we are getting the m2m field change or not? If we get a change, we let the signal handle it, otherwise, we'll trigger it manually through post_save().
Or another approach which allows us to query the newly created object separately after it's created/updated and then trigger the webhook.
Any help would be appreciated.
Thanks!