evilmind
evilmind

Reputation: 121

Group by in manytomany fields in Django

Ive got a simple task. There are two models

class Song(models.Model):
    song_title = models.CharField(max_length=200)
    song_genres = models.ManyToManyField(Genres, null=True, related_name='genres')
    ...

class Genre(models.Model):
    genre_title = models.CharField(max_length=50)
    genre_uri = models.SlugField(max_length=100, unique=True, blank=True)
    ...

I need to get list of most popular tags with song's count. For example:

[{<Genres: Pop>, 20}, {<Genres: Rap>, 15} ...]

For foreign key i can use

Song.objects.annotate(count=Count('song_genres')).order_by('-count')[:5]

but it doesn't work with manytomany fields. Any help would be much appreciated.

Upvotes: 3

Views: 1552

Answers (1)

Sachin Gupta
Sachin Gupta

Reputation: 404

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.

Upvotes: 3

Related Questions