[Answered ]-How to order Django query based on the sum of a specific field grouped by another field?

1👍

You can annotate the PlayerProfiles with the umber of goals, and then order by that number and slice, so:

from django.db.models import Count

PlayerProfile.objects.annotate(
    total_goals=Count('goal_maker')
).order_by('-total_goals')[:3]

Leave a comment