Onyilimba
Onyilimba

Reputation: 1217

Perform action when a certain field changes in the django admin

I was wondering how to do something for case like this say I have a model like this

class ModelA(models.Model):
    paid = models.BooleanField(default=False)
    amount = models.DecimalField()

and you want to perform an action like add 1? to amount when the boolean field is checked. not the first save but subsequent save when changing paid field in the admin how would that be done? and signals be use for such? can one do a method like this and add it to signal?

def test_stuff_change(instance, sender, *args, **kwargs):
    if paid == True:
    #what ever logic and statement goes in here

can this be done on change fields?

Upvotes: 1

Views: 926

Answers (1)

Ykh
Ykh

Reputation: 7717

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

@receiver(post_save, sender=ModelA)
def test_stuff_change(instance, sender, *args, **kwargs):
    if instance.paid:
        instance.amount += 1
        instance.paid = False
        instance.save()

If you don't want instance.paid = False after instance.amount += 1,do like:

class ModelA(models.Model):
    paid = models.BooleanField(default=False)
    is_add = models.BooleanField(default=False)
    amount = models.DecimalField()

@receiver(post_save, sender=ModelA)
def test_stuff_change(instance, sender, *args, **kwargs):
    if instance.paid and not instance.is_add:
        instance.amount += 1
        instance.is_add= True
        instance.save()

If you mean add amount when paid toggle, do like:

class ModelA(models.Model):
    paid = models.BooleanField(default=False)
    amount = models.DecimalField()

    def save(self, *args, **kwargs):
        if not self.id:
            pass 
        else:
            this = ModelA.objects.get(id=self.id)
            if this.paid != self.paid :
                self.amount += 1
        return super(ModelA, self).save(*args, **kwargs)

Upvotes: 3

Related Questions