Search code examples
pythondjangodjango-modelsdjango-signals

Django post save signal not updating the database


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

Solution

  • 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.