Friday, July 7, 2023

Re: Calculations

Or, you can combine annotations and expressions to do something like this:

qs = LoanInformation.objects.annotate(outstanding=F("amount_to_pay") - Func(F("payments__amount"), function="SUM))
loan = qs.get(id=loan_id)
loan.outstanding

On Friday, July 7, 2023 at 4:03:09 PM 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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/700326cd-ec0c-471d-9e51-8a30fb9fd64bn%40googlegroups.com.

No comments:

Post a Comment