[Answered ]-Django: Overriding the Save (Either Model or Admin Section)

2👍

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.

0👍

I’d take a slight performance hit in favour of avoiding the duplication of the voucher count information (call me old-fashioned).

In stead of saving the voucher count in Person.vc, I’d evaluate the voucher count when needed by creating a function for that in the Voucher object manager:

def get_voucher_count(self, person):
    return self.filter(ps=person).count()

0👍

OK, I manage to work it out (with the help of Shang Wang & Ytsen de Boer answer as well, which I’m grateful for). The way which I did it was to create an instance of the object Person and take away from it there.

Fortunately enough, I quick time check the doc’s which Shang just showed me (and look way deeper as well). Below is the way to do it:

@receiver(post_save, sender = Voucher, dispatch_uid = "voucher_identifier")
def decrease_quota(sender, instance, **kwargs):
obj = Person.objects.get(pk = instance.ps.id)
if obj.vc < 4 and obj.vc > 0:
    obj.vc = obj.vc - 1
    obj.save()

Of course I have to do abit more to it (simple validations and stuff like that), but this how I needed it.

Leave a comment