[Django]-Django: Grouping and ordering across foreign keys with conditions

6๐Ÿ‘

โœ…

You can use the same field in both values and annotate.

You have the primary key of the Song object (you could just use song instead of song__id), so use

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

For your second question, do a separate query with song__artist as the field in values and 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]
๐Ÿ‘คagf

0๐Ÿ‘

agf has already showed you how to group by song_artist. What I would do to get the actual Song object is store it in memcached, or if the method you are calling is rather simplistic make it a static method or a class method. You might could also initialize a Song object with the data from the query and not actually save it to get access to this method. Might help to know the details of the methods you want to call from the Song object.

๐Ÿ‘คBenH

Leave a comment