[Answered ]-Django: aggregate django fields to avoid N + 1 problem

1👍

You can filter with:

from django.db.models import Count, F

course_payments = CourseStudentPayment.objects.filter(
    course_student__presence__date__gt=F('start_date')
).annotate(presence_count=Count('course_student__presence'))

The CourseStudentPayment objects will have an extra attribute .presence_count with the number of Presences after the start_date of the CourseStudentPayment object.

This will however leave out CourseStudentPayments without any Presence, you can include these with:

from django.db.models import Count, F

course_payments = CourseStudentPayment.objects.annotate(
    presence_count=Count(
        'course_student__presence',
        filter=Q(course_student__presence__date__gt=F('start_date')),
    )
)

Leave a comment