Django Signals - pre_save()


Django tip:

To execute some code dealing with another part of your application before the object gets saved to the database, you have to use a pre_save signal.

That way, the signal is sent at the beginning of a model's save() method.

For example:

from django.db.models.signals import pre_save
from django.dispatch import receiver


@receiver(pre_save, sender=Order)
def valid_order(sender, instance, **kwargs):
    inventory_item = Inventory.objects.get(id=instance.inventory_item.id)

    if instance.quantity > inventory_item.quantity:
        raise Exception("There are not enough items in the inventory.")