in addition to what @Thomas said you need to first perform an aggregated 
sum on the payments model hence the need for ... 
loan.payments_set.aggregrate(models.Sum('amount'))
the above returns the sum of all payment related to your loan instance from 
which you can now subtract from loan.amount_to_pay

you can read this post for further 
clarity 
https://medium.com/@clemcy9/performing-aggregate-sum-in-postgresql-django-3472e5248bb3

On Friday, 7 July 2023 at 16:03:09 UTC+1 Thomas Couch wrote:

> Hi Abdou, have a look at aggregation (
> https://docs.djangoproject.com/en/4.2/topics/db/aggregation/)
>
> In this case I think you'll want something like:
>
> ```
> from django.db.models import Sum
>
> # Where loan = the LoanInformation instance you're interested in
> outstanding_balance = loan.amount_to_pay - 
> loan.payments_set.aggregate(Sum("amount"))
> ```
>
>
> On Thursday, July 6, 2023 at 5:39:50 PM UTC+1 Abdou KARAMBIZI wrote:
>
>> class LoanInformation(models.Model):
>>     id = models.AutoField(primary_key=True)
>>     customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
>>     amount_to_pay = models.IntegerField()
>>  
>>     def __str__ (self):
>>         return self.id
>>
>> class Payments(models.Model):
>>     id = models.AutoField(primary_key = True)
>>     loan = models.ForeignKey(LoanInformation,on_delete=models.CASCADE)
>>     amount = models.IntegerField()
>>     paidon = models.DateField(auto_now=True)
>>
>>     def __str__ (self):
>>         return self.id
>>
>>
>>
>> I want to display the result of  "amount_to_pay - sum of amount"
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9e8a4bfd-d18a-4df5-a01c-2f4240511a98n%40googlegroups.com.

Reply via email to