晚上好。 目的是在创建 Transfer 模型时,将 sum 字段从 whom_from 中减去并添加到 whom_to Bill的模型。据我了解,这需要通过save()完成,但是显然我没有正确设置它。可能是什么问题?
models.py
class Bill(models.Model):
title = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=19, decimal_places=2,
validators=[MinValueValidator(0)], default=0)
def __str__(self):
return self.title
class Transfer(models.Model):
whom_from = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_from')
whom_to = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_to')
sum = models.DecimalField(max_digits=19, decimal_places=2, validators=[MinValueValidator(0)], default=0)
def save(self, *args, **kwargs):
self.whom_to.amount = self.whom_to.amount + self.sum
self.whom_from.amount = self.whom_from.amount - self.sum
super(Transfer, self).save(*args, **kwargs)