Improve readability

Added additional comments to improve readability of the genre graph
related code.
This commit is contained in:
Chris Shyi
2018-07-26 02:37:53 -04:00
parent 54c541426c
commit 765141c024
4 changed files with 39 additions and 29 deletions

View File

@@ -186,13 +186,11 @@ def add_artist_genres(headers, artist_objs):
# get_artists_in_genre {{{ #
def get_artists_in_genre(user, genre, max_songs):
def get_artists_in_genre(user, genre):
"""Return count of artists in genre.
:user: User object to return data for.
:genre: genre to count artists for. (string)
:max_songs: max total songs to include to prevent overflow due to having
multiple artists on each track.
:returns: dict of artists in the genre along with the number of songs they
have.
@@ -204,19 +202,10 @@ def get_artists_in_genre(user, genre, max_songs):
total_artist_counts = tracks_in_genre.aggregate(counts=Count('artists'))['counts']
processed_artist_counts = {}
# songs_added = 0
for artist in user_artists:
# hacky way to not have total count overflow due to there being multiple
# artists on a track
# if songs_added + artist.num_songs <= max_songs:
# processed_artist_counts[artist.name] = artist.num_songs
# songs_added += artist.num_songs
processed_artist_counts[artist.name] = round(artist.track_set
.filter(genre=genre_obj, users=user)
.count() * track_count / total_artist_counts, 2)
# processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
# processed_artist_counts = {artist.name: artist.num_songs for artist in artist_counts}
# pprint.pprint(processed_artist_counts)
return processed_artist_counts
# }}} get_artists_in_genre #

View File

@@ -176,10 +176,30 @@ def get_genre_data(request, user_secret):
genre_counts = (Track.objects.filter(users__exact=user)
.values('genre')
.order_by('genre')
# annotates each genre and not each Track, due to the earlier values() call
.annotate(num_songs=Count('genre'))
)
# genre_counts is a QuerySet with the format
# [{'genre': 'classical', 'num_songs': 100}, {'genre': 'pop', 'num_songs': 50}...]
for genre_dict in genre_counts:
genre_dict['artists'] = get_artists_in_genre(user, genre_dict['genre'], genre_dict['num_songs'])
genre_dict['artists'] = get_artists_in_genre(user, genre_dict['genre'])
'''
Now genre_counts has the format
[
{'genre': 'classical',
'num_songs': 100,
'artists': {
'Helene Grimaud': 40.5,
'Beethoven': 31.2,
'Mozart': 22...
}
},
{'genre': 'pop',
'num_songs': 150,
'artists': {...}
},...
]
'''
print("*** Genre Breakdown ***")
pprint.pprint(list(genre_counts))
return JsonResponse(data=list(genre_counts), safe=False)