Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按ForeignKey分组,并且ForeignKey是另一个';步骤';离开_Python_Database_Django_Orm - Fatal编程技术网

Python 按ForeignKey分组,并且ForeignKey是另一个';步骤';离开

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

在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()
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]

然后查询就会更清楚。

这正是我想要的,谢谢。我还没意识到你可以像宋剧那样在一段关系中计算!