In Django, I have an app with models like this:
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?
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:
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).
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.
Then queries will be much clearer.