Django: grouping and arranging foreign keys with conditions

I have some Django models that record listener habits (a bit like Last.fm), for example:

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)
    user = models.ForeignKey(User)
    time = models.DateTimeField()

class User(models.Model):
    # doesn't really matter!

I would like to have a user page where I can show the best songs they listened to last month. What is the best way to do this?

The best I've come up with so far:

SongPlay.past_month
    .filter(user=user)
    .values('song__title', 'song__id', 'song__artist__name')
    .annotate(plays=Count('song'))
    .order_by('-plays')[:20]

Above past_monthis a manager who simply filters games from the last month. Suppose we already have the correct object userto filter.

I think my two questions are:

  • , plays?
    , , values. - , .

  • SongPlay Artist? , .

+3
2

values annotate.

Song ( Song song__id),

Song.objects.get(id=...)

song__artist values annotate:

from django.db.models import Count

SongPlay.past_month
    .filter(user=user)
    .values('song__artist')
    .annotate(plays=Count('song__artist'))
    .order_by('-plays')[:20]
+3

agf , song_artist. , , memcached, , , , . Song . , Song.

0

All Articles