Home > Software design >  Django get last value for each forgin key values
Django get last value for each forgin key values

Time:09-23

In models.py

class loan(models.Model):
    completed=models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True,null=True)
    application_id=models.CharField(max_length=100,unique=True)

class topay(models.Model):
    loanapplication=models.ForeignKey(loan,on_delete=models.CASCADE,null=True)
    paymentdate=models.DateField(null=True, blank=True)
    

How to get last paymentdate for every loan application
In views.py

topay.objects.filter().values().annotate(last=Max('paymentdate'))

CodePudding user response:

to get each loan latest topay you can filter like this

loan.objects.annotate(
    maxpaydate=Max("topay__paymentdate"),
).values("id", "maxpaydate")
  • Related