Browse Source

Fixed duplicate key error in save_track_obj

Can't create Track object without the artists/user so get_or_create
doesn't work properly.
master
Kevin Mok 7 years ago
parent
commit
ea5990d048
  1. 1
      spotifyvis/models.py
  2. 28
      spotifyvis/utils.py
  3. 8
      spotifyvis/views.py

1
spotifyvis/models.py

@ -2,6 +2,7 @@ from django.db import models
# id's are 22 in length in examples but set to 30 for buffer
MAX_ID = 30
# Artist {{{ #

28
spotifyvis/utils.py

@ -80,7 +80,6 @@ def parse_library(headers, tracks, library_stats, user):
# save_track_obj {{{ #
def save_track_obj(track_dict, artists, user):
"""Make an entry in the database for this track if it doesn't exist already.
@ -91,22 +90,25 @@ def save_track_obj(track_dict, artists, user):
"""
print(track_dict['name'])
new_track, created = Track.objects.get_or_create(
track_id=track_dict['id'],
year=track_dict['album']['release_date'].split('-')[0],
popularity=int(track_dict['popularity']),
runtime=int(float(track_dict['duration_ms']) / 1000),
name=track_dict['name'],
)
# have to add artists and user after saving object since track needs to
# have ID before filling in m2m field
if created:
track_query = Track.objects.filter(track_id__exact=track_dict['id'])
if len(track_query) != 0:
return track_query[0], False
else:
new_track = Track.objects.create(
track_id=track_dict['id'],
year=track_dict['album']['release_date'].split('-')[0],
popularity=int(track_dict['popularity']),
runtime=int(float(track_dict['duration_ms']) / 1000),
name=track_dict['name'],
)
# have to add artists and user after saving object since track needs to
# have ID before filling in m2m field
for artist in artists:
new_track.artists.add(artist)
new_track.users.add(user)
new_track.save()
return new_track, created
return new_track, True
# }}} save_track_obj #

8
spotifyvis/views.py

@ -175,6 +175,8 @@ def user_data(request):
# }}} user_data #
def test_db(request):
"""TODO
"""
user_id = "polarbier"
context = {
'user_id': user_id,
@ -184,13 +186,11 @@ def test_db(request):
def get_artist_data(request, user_id):
"""TODO
"""
# TODO: not actual artists for user
# PICK UP: figure out how to pass data to D3/frontend
print(user_id)
# user = User.objects.get(user_id=user_id)
artist_counts = Artist.objects.annotate(num_songs=Count('track'))
processed_artist_data = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
# for artist in artist_counts:
# print(artist.name, artist.num_songs)
return JsonResponse(data=processed_artist_data, safe=False)
Loading…
Cancel
Save