1 回答
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
TA贡献1876条经验 获得超7个赞
信号应该适合您在这里想要的。StudentPayment在某些操作(例如保存或删除对象)后会触发信号,以便您可以在保存或删除对象时执行功能。
此时,您可能希望余额Wallet是支付给该钱包的所有金额的总和。
from django.db.models import Sum
from django.db.models.signals import (
post_delete,
post_save,
)
from django.dispatch import receiver
class Wallet(models.Model):
...
balance = models.DecimalField(decimal_places=2, max_digits=100, default=0.00)
...
class StudentPayment(models.Model):
...
wallet = models.ForeignKey(
Wallet,
on_delete=models.SET_NULL,
null=True, related_name='students_payment')
amount = models.DecimalField(decimal_places=2, max_digits=100)
...
@receiver([post_save, post_delete], sender=StudentPayment)
def calculate_total_amount(instance, **kwargs):
wallet = instance.wallet
# Add together the amount of all `StudentPayment` objects for the wallet
total = StudentPayment.objects.filter(wallet=wallet).aggregate(
Sum('amount')
)['amount__sum']
wallet.balance = total
wallet.save(update_fields=['balance'])
添加回答
举报