how to get the last record from an object by field

Hello everyone, Im trying to get the last payment from each user:

Here is my model:

class Payment(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
amount = models.DecimalField(max_digits=7, decimal_places=2, default=‘0.00’)

class Student(models.Model):
id=models.AutoField(primary_key=True)
user=models.OneToOneField(User, on_delete=models.CASCADE, null=True)

Explanation:
One user has many payments. What i need is to get the last record of payment of the user to validate when he realized his last payment. What method or logic i need to use. Can anybody help me? Thanks.

Would something like this work?

Payment.objects.filter(user__username__iexact=some_username).latest()

You can adjust the filter based on how your user model is configured.

Without a date in your Payment class, I’m not sure how you’re going to validate when that last payment was made.

For the dates im using created_at and updated_at, looks like this:

class Payment(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
amount = models.DecimalField(max_digits=7, decimal_places=2, default=‘0.00’)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)

class Student(models.Model):
id=models.AutoField(primary_key=True)
user=models.OneToOneField(User, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)

Are you looking to get the most recent payment for all students, or are you looking to retrieve the most recent payment for a single student? (Or are you looking to get the most recent payment for the person who is currently logged on and looking at that page?)

For all students i guess

Let’s start with the simple case.

Say you have an instance of Student named student.

Given student, how would you retrieve all the Payment objects that are associated with student?

If necessary, you may want to review the docs at: