亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據其他模型 Django 的值更改模型的值

根據其他模型 Django 的值更改模型的值

子衿沉夜 2023-08-15 16:38:35
我有一個模型Wallet和StudentPayment. 每次我添加或更新 StudentPayment 時,Wallet余額都應根據添加或更新的情況而變化StudentPayment。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)    ...例如:如果我添加1000金額的付款,錢包余額也應該更改為1000,我知道該怎么做,但不知道如何處理更新,例如:如果我將付款金額更改為900,錢包余額也應該發生變化。感謝任何幫助)我嘗試使用重寫 save() 方法來實現,但沒有任何效果
查看完整描述

1 回答

?
幕布斯6054654

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'])


查看完整回答
反對 回復 2023-08-15
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號