Python 按ForeignKey分组,并且ForeignKey是另一个';步骤';离开
在Django,我有一个应用程序,其模型如下:Python 按ForeignKey分组,并且ForeignKey是另一个';步骤';离开,python,database,django,orm,Python,Database,Django,Orm,在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) t
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()
SongPlay.objects.values('song__id', 'song__artist__name', 'song__title')
.annotate(Count('song')).order_by('-song__count')[:10]
我希望能够制作一张播放次数最多的歌曲和播放次数最多的艺术家的图表。我如何使用Django的ORM来进行分组
和计数
目前,我正在做这样的事情:
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()
SongPlay.objects.values('song__id', 'song__artist__name', 'song__title')
.annotate(Count('song')).order_by('-song__count')[:10]
…以获得前10首歌曲,以下是:
SongPlay.objects.values('song__artist__id', 'song__artist__name')
.annotate(Count('song__artist')).order_by('-song__artist__count')[:10]
…获得前十名艺术家
有没有更简单的方法来实现这一点?我真的不喜欢指定值
,我更喜欢按照(song\u object,count)
和(artist\u object,count)
的行获取元组
有什么明显的我错过了吗?谢谢 您应该从最终想要获取的对象开始构建查询
Artist.objects.annotate(played=Count('song__songplay')).order_by('-played')[:10]
Song.objects.annotate(played=Count('songplay')).order_by('-played')[:10]
然后查询就会更清楚。这正是我想要的,谢谢。我还没意识到你可以像宋剧那样在一段关系中计算!