1 回答
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
信號(hào)應(yīng)該適合您在這里想要的。StudentPayment在某些操作(例如保存或刪除對(duì)象)后會(huì)觸發(fā)信號(hào),以便您可以在保存或刪除對(duì)象時(shí)執(zhí)行功能。
此時(shí),您可能希望余額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'])
添加回答
舉報(bào)
