0

i have the following model


class FeeModel(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    total_fee=models.IntegerField(default=100000)
    paid_fee=models.IntegerField()
    remaining_fee=models.IntegerField(default=0)

i need the remaining_fee to be filled by the result of (total_fee - paid_fee). How would i do that?

1
  • If the solution below works for you, consider accepting the answer. Thanks. Commented Feb 28, 2022 at 19:49

1 Answer 1

3

You can do this in numerous ways and places. A pre_save signal is one approach.

(In models.py, below your FeeModel class)

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=FeeModel)
def set_remaining_fee(sender, instance, *args, **kwargs):
    instance.remaining_fee = (instance.total_fee - instance.paid_fee)

How this works: A user enters the values for total_fee and paid_fee into a form. Upon submit and just before save(), the signal calculates the difference and applies it to the remaining_fee field. Note that this will run every time the model instance is saved.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.