使用Django中的save函数覆盖不同模型中的值

时间:2015-11-09 03:28:55

标签: django django-models

我正在开展一个用户可以在帐户中添加现金的项目。因此,我有两个模型,UserProfile,其中包含用户的基本信息(包括他们的帐户余额),以及允许他们添加现金的交易。当提交trasnaction时,有没有办法更新(UserProfile)中的余额字段?

以下是我的models.py的样子:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    balance = models.DecimalField(max_digits=15, decimal_places=2, default=0)

class Transaction(models.Model):
    user = models.ForeignKey(UserProfile)
    amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)

    def save(self, *args, **kwargs):
        self.user.balance = self.amount
        super(Transaction, self).save(*args, **kwargs)

所以基本上我想将UserProfile中的balance字段更新为在Transaction模型中输入的值。任何人都知道我是如何实现这一目标的?感谢

1 个答案:

答案 0 :(得分:3)

您的示例看起来很好,除了一个问题:您在用户个人资料中缺少save()

class Transaction(models.Model):
    user = models.ForeignKey(UserProfile)
    amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)

    def save(self, *args, **kwargs):
        self.user.balance = self.amount
        super(Transaction, self).save(*args, **kwargs)
        self.user.save()