Django post 保存信号不更新数据库
Django post save signal not updating the database
我不明白为什么这个信号不起作用。同样的代码工作了一次,但之后我从管理员中删除了对象并再次 运行 它停止工作。
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
amount_paid = FinancePending.objects.values_list('amountPaid', flat=True)
amount_paid = list(amount_paid)
total_amount = FinancePending.objects.values_list('TotalAmount', flat=True)
total_amount = list(total_amount)
# total - paid
TotalFee = [int(s.replace(',', '')) for s in total_amount]
AmountPaid = [int(s.replace(',', '')) for s in amount_paid]
finance_pending = FinancePending.objects.all()
i = 1
while i <= len(TotalFee):
amount_pending = TotalFee[i-1] - AmountPaid[i-1]
amountpending = FinancePending.objects.filter(invoiceNumber=i)
amountpending.AmountPending = amount_pending
i = 1 + i
因为信号 post_save only triggered after call save() method. You should use post_delete 而不是。
您没有调用 save()
方法,这就是它没有保存的原因。但我不认为它是django prespective 的优化实现。你可以简单地尝试使用 update()
:
from django.db.models import F
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
FinancePending.objects.update(AmountPending=F('TotalAmount')-F('amountPaid'))
此外,更新每个创建 FinancePending
实例的对象是没有意义的。可能你应该只更新创建的对象。像这样:
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
instance.AmountPending=instance.TotalAmount-instance.amountPaid
instance.save()
最后,请在命名属性和函数名称时遵循pep8 style guide。
我不明白为什么这个信号不起作用。同样的代码工作了一次,但之后我从管理员中删除了对象并再次 运行 它停止工作。
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
amount_paid = FinancePending.objects.values_list('amountPaid', flat=True)
amount_paid = list(amount_paid)
total_amount = FinancePending.objects.values_list('TotalAmount', flat=True)
total_amount = list(total_amount)
# total - paid
TotalFee = [int(s.replace(',', '')) for s in total_amount]
AmountPaid = [int(s.replace(',', '')) for s in amount_paid]
finance_pending = FinancePending.objects.all()
i = 1
while i <= len(TotalFee):
amount_pending = TotalFee[i-1] - AmountPaid[i-1]
amountpending = FinancePending.objects.filter(invoiceNumber=i)
amountpending.AmountPending = amount_pending
i = 1 + i
因为信号 post_save only triggered after call save() method. You should use post_delete 而不是。
您没有调用 save()
方法,这就是它没有保存的原因。但我不认为它是django prespective 的优化实现。你可以简单地尝试使用 update()
:
from django.db.models import F
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
FinancePending.objects.update(AmountPending=F('TotalAmount')-F('amountPaid'))
此外,更新每个创建 FinancePending
实例的对象是没有意义的。可能你应该只更新创建的对象。像这样:
@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
instance.AmountPending=instance.TotalAmount-instance.amountPaid
instance.save()
最后,请在命名属性和函数名称时遵循pep8 style guide。