当Django管理员中的某个字段发生更改时执行操作

时间:2018-10-17 23:19:29

标签: python django django-admin

我想知道如何处理这种情况 说我有这样的模型

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

,您要执行加1之类的操作吗?选中布尔字段时的数量。不是第一次保存,而是在管理员中更改付费字段时的后续保存,将如何进行?和信号用于这样的? 可以做这样的一种方法并将其添加到信号中吗?

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

这可以在更改字段上完成吗?

1 个答案:

答案 0 :(得分:1)

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()

如果您不想在instance.paid = False之后使用instance.amount += 1,请执行以下操作:

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()

如果您是指付费切换时增加金额,请执行以下操作:

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)