[Django]-Group by in manytomany fields in Django

3👍

Assuming related_name on song model is ‘songs’, because it should be.

Genres.objects.annotate(songs_count=Count('songs')).order_by('-songs_count')[:10].values('id', 'songs_count')

This will give you id of all top 10 generes and songs_count in them.

Leave a comment