Finding the highest amount of an instance in django models

I have two models that have a foreign key relationship to each other.

One of the models is a Student and the other is Grade.

The issue I'm having it I'm getting the values I want with model methods in the template. so what I'm trying to do is I want the Student with the highest grade score all the way to the lowest.

How actually can I achieve this?

class Student(models.Model):
    user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="student")
    student_name = models.CharField(max_length=15)
    
    def get_grades(self):
        today = datetime.date.today()
        return self.student_grade.filter(Date_created__year=today.year,Date_created__month=today.month)
    def get_passed(self):
        today = datetime.date.today()
        return self.student_grade.filter(Date_created__year=today.year,Date_created__month=today.month, State="Passed")

States = (("Pending","Pending"),("Passed","Passed"),("Failed","Failed"))
class Grade(models.Model):
    student = models.ForeignKey(Student,on_delete=models.SET_NULL,blank=True, null=True,related_name="student_grade")
    State = models.CharField(choices=States,default="Pending",max_length=26)
 

    def __str__(self):
        return self.student

You will need to use Django annotation to count the number of grades that have 'Passed', this should work for you:

from django.db.models import Count, Case, When, IntegerField

students = Student.objects.annotate(pass_marks=Count(
    Case(When(student_grade__state="Passed", then=1),
        output_field=IntegerField(),
    ))
)

You then have a queryset that you can work with in a view and a template that has all of your student information but also has a property called .pass_marks that will give you the number of passed grades.

If you want to condense this into just a few values or order it then you can use other Django functions like .values('student_name','pass_marks') and .order_by('-pass_marks')

Back to Top