Skip to content

Instantly share code, notes, and snippets.

@diek
Created April 24, 2022 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diek/cf3213060020eb63f3a0904c8f057787 to your computer and use it in GitHub Desktop.
Save diek/cf3213060020eb63f3a0904c8f057787 to your computer and use it in GitHub Desktop.
# This file must be saved in app/management/commands/upload_csv.py
# https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/
from chinook.models import Playlist, PlaylistTrack, Track
from django.core.management import BaseCommand
def get_playlisttrack():
data = []
with open('PlaylistTrack.csv') as infile:
next(infile)
for line in infile:
playlist_track = line.split('|')
data.append(playlist_track)
return data
class Command(BaseCommand):
# Provide help at command prompt for user
help = "Adds events"
# A command must define handle()
def handle(self, *args, **options):
playlists_tracks = get_playlisttrack()
for playlist_track in playlists_tracks:
pl = Playlist.objects.get(pk=playlist_track[0])
t = Track.objects.get(pk=playlist_track[1])
plt = PlaylistTrack.objects.create(playlist=pl, track=t)
plt.save()
self.stdout.write("Task completed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment