Django:如何创建从其他模型计算得出的模型?

时间:2019-03-17 03:35:13

标签: django

我有费用和收入模型。这两个模型应该成为称为余额的其他模型的基础。

哪里

balance.income = sum(incomes)
balance.expense = sum(expenses)
balance.rest = sum(incomes) - sum(expenses)

如何在Django中实现这种余额模型?期望是,每当收入和支出模型从用户那里获得新数据时,余额将自动计算。下面是我对那些模型的实现,但是需要修改Balance模型(这里只是为了介绍结构)。

from django.db import models

class User(models.Model):
    user_id = models.AutoField(primary_key=True)
    firstname = models.CharField(max_length=20)
    lastname = models.CharField(max_length=20)

    def __str__(self):
        return self.firstname

class Balance(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    currency = models.CharField(max_length=3, default='$')
    income = models.IntegerField(default=0)
    expense = models.IntegerField(default=0)
    rest = models.IntegerField(default=0)
    saving = models.IntegerField(default=0)

    def __str__(self):
        return str(self.rest)

class Expense(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField()
    category = models.TextField(default='')
    detail = models.TextField(default='')
    place = models.TextField(default='')
    amount = models.FloatField(default=0.0)

    def __str__(self):
        return self.detail

class Income(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField()
    detail = models.TextField(default='')
    amount = models.FloatField(default=0.0)

    def __str__(self):
        return self.detail

1 个答案:

答案 0 :(得分:0)

最简单的方法是重写.save()方法。请注意,通过命令行保存模型时将绕过此操作。

class Balance(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    currency = models.CharField(max_length=3, default='$')
    income = models.IntegerField(default=0)
    expense = models.IntegerField(default=0)
    rest = models.IntegerField(default=0)
    saving = models.IntegerField(default=0)

    def __str__(self):
        return str(self.rest)

    def save(self, *args, **kwargs):
        user_incomes = Income.objects.filter(user=self.user).aggregate(Sum('amount'))['amount_sum']
        user_expenses = Expense.objects.filter(user=self.user).aggregate(Sum('amount'))['amount_sum']
        self.income = user_incomes
        self.expense = user_expenses
        self.balance = user_incomes - user_expenses
        super(Balance, self).save(*args, **kwargs)