From 80f8aa5d663c33aa583b5b47749a6ef68132dcb8 Mon Sep 17 00:00:00 2001 From: Keannu Bernasol Date: Sun, 23 Jul 2023 23:15:52 +0800 Subject: [PATCH] Auto add courses post-migration based on csv records that we have --- stude/courses/models.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/stude/courses/models.py b/stude/courses/models.py index e9e6fca..809ae1b 100644 --- a/stude/courses/models.py +++ b/stude/courses/models.py @@ -1,3 +1,5 @@ +import os +from django.conf import settings from django.db.models.signals import post_migrate from django.dispatch import receiver from django.db import models @@ -14,6 +16,8 @@ class Course(models.Model): return self.name +''' +# Old Subject migration code @receiver(post_migrate) def populate_courses(sender, **kwargs): if sender.name == 'courses': @@ -26,3 +30,39 @@ def populate_courses(sender, **kwargs): Course.objects.get_or_create( name='Bachelor of Science in Data Science', shortname='BSDS') # Add more predefined records as needed +''' + + +# Create subjects based on records that we have +@receiver(post_migrate) +def populate_subjects(sender, **kwargs): + if sender.name == 'courses': + root_path = os.path.join(settings.MEDIA_ROOT, 'records') + csv_files = [f for f in os.listdir(root_path) if f.endswith('.csv')] + added_courses = 0 + existing_courses = 0 + print('Adding courses\n') + for csv_file in csv_files: + # The filename contains coursename + filename = os.path.splitext(csv_file)[0] + # Splitting the filename and constructing the shortname + shortname = '' + for word in filename.split(' '): + if word[0].isupper(): + shortname += word[0] + + if shortname != None: + # If course already exists with relevant info, skip over it + if (Course.objects.filter(name=filename, shortname=shortname).exists()): + + existing_courses += 1 + continue + + # Else add the course + else: + Course.objects.get_or_create( + name=filename, shortname=shortname) + added_courses += 1 + + print('Added', added_courses, 'courses') + print(existing_courses, 'existing courses skipped\n')