在 Django 的 manytomany 字段中分组
Group by in manytomany fields in Django
我有一个简单的任务。有两种型号
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)
...
我需要获取最流行标签的列表以及歌曲的数量。例如:
[{<Genres: Pop>, 20}, {<Genres: Rap>, 15} ...]
对于外键,我可以使用
Song.objects.annotate(count=Count('song_genres')).order_by('-count')[:5]
但它不适用于 manytomany 字段。任何帮助将不胜感激。
假设歌曲模型上的 related_name 是 'songs',因为它应该是。
Genres.objects.annotate(songs_count=Count('songs')).order_by('-songs_count')[:10].values('id', 'songs_count')
这将为您提供所有前 10 个流派的 ID 以及其中的 songs_count。
我有一个简单的任务。有两种型号
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)
...
我需要获取最流行标签的列表以及歌曲的数量。例如:
[{<Genres: Pop>, 20}, {<Genres: Rap>, 15} ...]
对于外键,我可以使用
Song.objects.annotate(count=Count('song_genres')).order_by('-count')[:5]
但它不适用于 manytomany 字段。任何帮助将不胜感激。
假设歌曲模型上的 related_name 是 'songs',因为它应该是。
Genres.objects.annotate(songs_count=Count('songs')).order_by('-songs_count')[:10].values('id', 'songs_count')
这将为您提供所有前 10 个流派的 ID 以及其中的 songs_count。