[Solved]-Django Aggregation Across Reverse Relationship

14👍

ProfileViews are related via a ForeignKey field, but it’s not as though the Profile model knows that

The Profile model actually does know that.
You should be able to do something like:

  Profile.objects.all().annotate(count_views=Count('profileview__pk')).order_by('count_views')

Edit: Here you can find Django docs about lookups that span relationships http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

4👍

Surely this will work:

Profile.objects.all().annotate(viewcount=Count('profileview')).order_by('-viewcount')

As Botondus says, the Profile model is aware of the backwards ForeignKey relationship.

Leave a comment