'Django ORM Query to show pending payments

Please guide me. I have below models under which a Student can enroll for a course which has a fees specified for it. Against that enrollment a student can make part payments. I am unable to create a query which will show me list of students with courses enrolled and total payment made for that enrollment.

class Course(models.Model):
    name = models.CharField(max_length=100)
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    student_class =  models.IntegerField(verbose_name="Class", help_text="Class", choices= STUDENT_CLASS)    
    fee = models.IntegerField()
    created_on = models.DateField(auto_now_add=True)

class Enrollment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    created_on = models.DateField(auto_now_add=True)

class Payment(models.Model):
    PAYMENT_CHOICES = [
        ('CAS', 'Cash'),
        ('CHQ','Cheque'),
    ]

    enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE)
    amount = models.IntegerField()
    mode = models.CharField(max_length=3, choices=PAYMENT_CHOICES)
    payment_date = models.DateField(auto_now_add=True)


Solution 1:[1]

I didn't test this, logically it should work but there might be some minor inaccuracy

student = Student.objects.get(id=1)
course = Course.objects.get(id=1)

paid_so_far = Payment.objects.filter(enrollment__student=student, enrollment__course=course).aggregate(Sum('amount'))['amount__sum']

if paid_so_far == course.fee:
    print('Course fully paid')


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Beikeni