Django Signals - m2m_changed()


Django tip:

To send a Django signal when a ManyToManyField is changed on a model instance, you can use the m2m_changed signal.

For example, this signal is sent if an item is added to the cart:

@receiver(m2m_changed, sender=Cart.items.through)
def cart_update_total_when_item_added(sender, instance, action, *args, **kwargs):
    if action == 'post_add':
        total = Decimal(0.00)

        for item in instance.items.all():
            total += item.price

        instance.total = total
        instance.save()