在Django中相对于另一个元素自动增加一个值

时间:2015-12-01 09:58:41

标签: django django-models

我有一个Django模型:

projectId = models.CharField(max_length=250)
interfaceVersion = models.CharField(max_length=20,blank=False,verbose_name = "InterFace Version")
dataSetVersion = models.SmallIntegerField(blank=False , verbose_name= "Data Set Version")
numberOfRetries = models.IntegerField(null = True ,blank = True , verbose_name= "Number of Retries")
retryTimeInterval = models.IntegerField(null = True ,default=30 , verbose_name= "Retry Time Interval")

如果我更改numberOfRetriesretryTimeInterval的值并保存,那么interfaceversion应该是自动增量。怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用Signals来解决此问题。

from django import dispatch
from django.db.models.signals import pre_save
# import your model


@dispatch.receiver(pre_save, sender=MyModel)
def my_pre_save_tasks(sender, instance, **kwargs):
    old = MyModel.objects.get(pk=instance.pk)
    if old.numberOfRetries != instance.numberOfRetries or old.retryTimeInterval != instance.retryTimeInterval:
        instance.interfaceversion += 1