[英]Grouping by a ForeignKey, and ForeignKeys that are another 'step' away
In Django, I have an app with models like this: 在Django中,我有一个具有以下模型的应用程序:
class Artist(models.Model):
name = models.CharField()
class Song(models.Model):
artist = models.ForeignKey(Artist)
title = models.CharField()
class SongPlay(models.Model):
song = models.ForeignKey(Song)
time = models.DateTimeField()
I want to be able to do a chart of the most played songs and the most played artists. 我希望能够绘制出最多播放的歌曲和最多播放的歌手的图表。 How can I use Django's ORM to do a
GROUP BY
and a COUNT
like this? 如何使用Django的ORM进行类似的
GROUP BY
和COUNT
?
At the moment, I'm doing something like this: 目前,我正在执行以下操作:
SongPlay.objects.values('song__id', 'song__artist__name', 'song__title')
.annotate(Count('song')).order_by('-song__count')[:10]
...to get the top 10 songs, and this: ...以获取前10首歌曲,并且:
SongPlay.objects.values('song__artist__id', 'song__artist__name')
.annotate(Count('song__artist')).order_by('-song__artist__count')[:10]
...to get the top 10 artists. ...获得前十名的艺术家。
Is there an easier way to achieve this? 有没有更简单的方法来实现这一目标? I don't really like specifying the
values
, I'd rather get tuples along the lines of (song_object, count)
and (artist_object, count)
. 我真的不喜欢指定
values
,我宁愿按照(song_object, count)
和(artist_object, count)
获取元组。
Is there something obvious I've missed? 有什么明显的我想念的吗? Thanks!
谢谢!
You should start building your queries from the objects that you want to get in the end. 您应该从最后想要获得的对象开始构建查询。
Artist.objects.annotate(played=Count('song__songplay')).order_by('-played')[:10]
Song.objects.annotate(played=Count('songplay')).order_by('-played')[:10]
Then queries will be much clearer. 这样查询将更加清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.