try out django
[mlpccg-meta.git] / meta / management / commands / csvimport.py
diff --git a/meta/management/commands/csvimport.py b/meta/management/commands/csvimport.py
new file mode 100644 (file)
index 0000000..0e91c82
--- /dev/null
@@ -0,0 +1,24 @@
+from django.core.management.base import BaseCommand, CommandError
+from meta.models import DeckListModel, TournamentModel, RecordModel
+from datetime import datetime
+
+import csv
+
+class Command(BaseCommand):
+    args = ''
+    help = 'Import tournament data from CSV'
+
+    def handle(self, *args, **options):
+        with open('data/tournaments.csv') as f:
+            for row in csv.DictReader(f, delimiter=','):
+                try:
+                    tournament = TournamentModel.objects.get(name__iexact=row['name'])
+                except TournamentModel.DoesNotExist:
+                    tournament = TournamentModel(name=row['name'], date=datetime.strptime(row['date'], '%Y-%m-%d'))
+                tournament.save()
+
+                decklist = DeckListModel(name=row['decklist_name'], url=row['decklist_url'])
+                decklist.save()
+
+                record = RecordModel(placement=int(row['placement']), tournament=tournament, decklist=decklist, verified=True)
+                record.save()