-1

Im not getting why this signal is not working. This same code worked once but after that i deleted the objects from admin and ran it again and it stopped working.

@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

2 Answers2

2

You did not call save() method, that is why it is not saving. But I do not think it is a optimized implementation from django's prespective. You can simply try like this using 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'))

Also, it does not make sense to update each and every object one instance of FinancePending is created. Probably you should only update the object which was created. Like this:

@receiver(post_save, sender=FinancePending)
def calcualate_FinancePending(sender, instance, created, **kwargs):
    instance.AmountPending=instance.TotalAmount-instance.amountPaid
    instance.save()

Finally, please follow pep8 style guide when naming your attributes and function names.

ruddra
  • 50,746
  • 7
  • 78
  • 101
0

Because signal post_save only triggered after call save() method. You should use post_delete instead.

King Peanut
  • 116
  • 3