计算 2 个字段的组合

Count combination of 2 fields

我想要每个电台一首歌的所有播放量。

class Airplay(Timestamps):
    song = models.ForeignKey(Song, on_delete=models.CASCADE)
    radio = models.ForeignKey(Radio, on_delete=models.CASCADE)
    airedAt = models.DateTimeField(blank=True)

我试着这样计算airplay

Airplay.objects.all().annotate(play_count=Count(Concat('song__id', 'radio__id'), distinct=True)).order_by('play_count')

我看到歌曲 x 电台组合出现了好几次。但是 play_count 总是 1。

试试这个:

Airplay.objects.values('song', 'radio').annotate(play_count=Count('*')).order_by('play_count')

这将计算 song 实例在 radio 实例上播放的次数。