如何在 Django 中实现交易和账户系统?



我正在构建一个存储交易和账户的个人理财应用程序。每笔交易都会影响账户余额。我将如何在我的应用程序中实现这一点?尽管在互联网上搜索了一段时间,但我还没有找到具体的答案。

models.py

class Account(models.Model):
DateCreated = models.DateTimeField()
AccountName = models.SlugField(max_length= 100, primary_key=True)
UserID = models.ForeignKey(MyUser, on_delete=models.CASCADE)      
Type = models.CharField(max_length= 20)
Balance = models.DecimalField(max_digits=19, decimal_places=8)
Value = models.DecimalField(max_digits=19, decimal_places=8)
class Transaction(models.Model):
TypeChoices = (
('Income', 'Income'),
('Expense', 'Expense'),
('Transfer', 'Transfer'),
)
CategoryChoices = (
('Rent', 'Rent'),
('Utilities', 'Utilities'),
('Food', 'Food'),
('Leisure', 'Leisure'),
('Insurance', 'Insurance'),
('Gas', 'Gas'),
('Savings', 'Savings'),
('Investment', 'Investment'),
('Phone Payment', 'Phone Payment'),
('Gym Payment','Gym Payment'),
('Salary', 'Salary'),
('Asset', 'Asset'),
('Miscellaneous', 'Miscellaneous'),
('Transfer', 'Transfer'),
)
AccountName = models.ForeignKey(Account, on_delete=models.CASCADE)
UserID = models.ForeignKey(MyUser, on_delete=models.CASCADE)
Date = models.DateField()
Type = models.CharField(max_length = 8, choices = TypeChoices)
Entity = models.CharField(max_length = 100)
Description = models.CharField(max_length = 200)
BudgetType = models.CharField(max_length = 20, choices = CategoryChoices)
Amount = models.DecimalField(max_digits=19, decimal_places=8)

我目前已创建允许用户创建、更新和删除交易和帐户的视图,但没有影响帐户余额的交易。实现这一点的最佳方法是什么?

您可以在事务模型中使用以下代码 (我测试过(

def save(self, *args, **kwargs):
self.AccountName.Balance += self.Amount
self.AccountName.save()
super(Transaction, self).save(*args, **kwargs) # Call the real save() method

此函数将在删除对象之前减少余额中的金额。

def delete(self, *args, **kwargs):
self.AccountName.Balance -= self.Amount
self.AccountName.save()
super(Transaction, self).delete(*args, **kwargs) 

如果您想在更新金额后更改余额,您可以使用以下信号:

@receiver(pre_save, sender=Transaction)
def update_balance_account(sender, instance, update_fields=None, **kwargs):
trans = Transaction.objects.get(AccountName=instance.AccountName, id=instance.id, UserID=instance.UserID)
instance.AccountName.Balance -= trans.Amount
instance.AccountName.save()

最新更新