Vlad the Impala
Vlad the Impala

Reputation: 15872

Sorting based on the count in a related field in Django

I have two models, Image and Tag. Each Image object can have more than one Tag associated with it, and I want to find my most frequently used tags. How would I go about this? It seems easy enough but I can't seem to figure it out.

Upvotes: 1

Views: 93

Answers (1)

Wolph
Wolph

Reputation: 80011

Django has (only recently) acquired Aggregate support, so now you could do something like this:

from django.db.models import Count
Tag.objects.annotate(img_count=Count('image')).order_by('img_count')

Upvotes: 1

Related Questions