1 回答

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'])
添加回答
舉報