Search code examples
pythonsqldjangosavemodels

Django: Overriding the Save (Either Model or Admin Section)


I've been playing around with Django recently, however I'm stuck on how to approach this problem. I have a 'Person' model which has a one to many relationship with a 'Voucher' Model. Now the person has a quota and each time a Voucher is generated, the quota will decrease by one. What I'm stuck on is doing this through the save method. So how does one do this?

Below are my models:

class Person(AbstractDetail):
# Note: Model to maintain information about Person
     vc = models.IntegerField(default = 3, verbose_name = 'Vouchers', 
     null = False, validators = [ validate_voucher ])

class Voucher(models.Model):
# Note: Model to maintain information about Voucher
     vc = models.CharField (max_length = 25, verbose_name = 'Voucher ID',
                     help_text = 'Voucher Identifier')
     ps = models.ForeignKey(Person, on_delete = models.CASCADE,
                       verbose_name = 'Person')

Solution

  • Don't do it in save(), it's easily messed up with django. Try to use django signal post_save():

    from django.db.models.signals import post_save
    
    @receiver(post_save, sender=Voucher)
    def decrease_quota(sender, instance, created, *args, **kwargs):
        if created:
            instance.vc -= 1
            instance.save()
    

    Check django doc for django signals.