用django更新帐户余额

时间:2016-10-09 21:30:42

标签: django

绝对n00b在这里,只是摆弄。试图制作一个非常简单的应用程序来跟踪我的个人开支。我有一个用于输入费用的课程,一个类别的课程和我的帐户余额的课程。计划是每次创建费用时在帐户余额中创建条目。

如何更新帐户余额?我必须从最新的费用条目中获取字段,以便在我的余额等级中进行数学运算,对吗?

这就是我所拥有的。任何帮助表示赞赏。

from django.db import models
from django.utils import timezone

class Category(models.Model):
    category = models.CharField(max_length=200,blank=False)

    def __str__(self):
        return self.category

class Balance(models.Model):
    date = models.DateTimeField(default=timezone.now)
    previous_balance = ????
    transaction = ????
    current_balance = previous_balance - transaction


class Expense(models.Model):
    date = models.DateTimeField(default=timezone.now)
    spender = models.ForeignKey('auth.User')
    description = models.CharField(max_length=200)
    category = models.ForeignKey(Category,default=1)
    ABN = 'ABN'
    ING = 'ING'
    ACCOUNT_CHOICES = (
        (ABN, 'ABN'),
        (ING, 'ING'),
    )
    account = models.CharField(
        max_length=30,
        choices=ACCOUNT_CHOICES,
        default=ABN,
    )
    amount = models.DecimalField(max_digits=10, decimal_places=2)

    def commit(self):
        self.commit_date = timezone.now()
        self.save()

    def __str__(self):
        return u"%s. Kosten: %s" % (self.description, self.amount)

2 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您希望能够在创建费用后获得当前余额。如果是这样,您可以使用Django's aggregation

from django.db.models import Sum

class Balance(models.Model):
   date = models.DateTimeField(default=timezone.now)
   # Keep the amount you start with
   starting_balance = models.IntegerField()

   # Get the Sum of all expenses and do some simple subtraction
   def get_current_balance(self):
       total_expenses = Expense.objects.all().aggregate(Sum('amount'))
       return self.starting_balance - total_expenses['amount__sum']

然后在您的观看中,您可以执行以下操作:

current_balance = some_balance_instance.get_current_balance()

答案 1 :(得分:0)

考虑到余额变更将由费用记录更改触发,您可以覆盖在费用模型上保存。然后可以在auto中维护balance table。

导入日期时间

class Expense(models.Model):
    date = models.DateTimeField(default=timezone.now)
    spender = models.ForeignKey('auth.User')
    description = models.CharField(max_length=200)
    category = models.ForeignKey(Category,default=1)
    ABN = 'ABN'
    ING = 'ING'
    ACCOUNT_CHOICES = (
        (ABN, 'ABN'),
        (ING, 'ING'),
    )
    account = models.CharField(
        max_length=30,
        choices=ACCOUNT_CHOICES,
        default=ABN,
    )
    amount = models.DecimalField(max_digits=10, decimal_places=2)


    def save(self, *args, **kwargs):
        super(Expense, self).save(*args, **kwargs)
        last_bal = Balance.objects.order_by('id').last()
        Balance.objects.create(date=datetime.datetime.now(), previouse_balance=last_bal.current_balance,
                               transaction=self, current_balance=last_bal.current_balance + self.amount)