51 lines
2.5 KiB
Python
51 lines
2.5 KiB
Python
import csv
|
||
from django.core.management.base import BaseCommand, CommandError
|
||
from ...models import Student
|
||
|
||
class Command(BaseCommand):
|
||
help = 'Import students from a CSV file'
|
||
|
||
def add_arguments(self, parser):
|
||
parser.add_argument('csv_file', type=str, help='The path to the CSV file')
|
||
|
||
def handle(self, *args, **kwargs):
|
||
csv_file_path = kwargs['csv_file']
|
||
|
||
with open(csv_file_path, newline='', encoding='utf-8-sig') as csvfile:
|
||
reader = csv.DictReader(csvfile)
|
||
|
||
for row in reader:
|
||
student_id = row.get('學號\nStudent\nID')
|
||
name = row.get('姓名\nName')
|
||
|
||
if not student_id or not name:
|
||
self.stdout.write(self.style.WARNING(f"Skipping row due to missing student_id or name: {row}"))
|
||
continue
|
||
|
||
grade = int(row.get('年級\nyear', 0)) if row.get('年級\nyear') else None
|
||
hope_admission_scheme = row.get('希望生\nHope admission\nscheme’ students').strip("'") == '通過'
|
||
tuition_waiver = row.get('減免\nTuition\nwaiver').strip("'") == '通過'
|
||
financial_assistance_disadvantaged_students = row.get('弱勢_生輔組\nFinancial assistances\nfor disadvantaged\nstudents').strip("'") == '通過'
|
||
loan = int(row.get('就學貸款\nLoan', 0)) if row.get('就學貸款\nLoan') else 0
|
||
emails = row.get('Email').split(';')
|
||
|
||
# Use the first email for simplicity; you can handle multiple emails as needed
|
||
email = emails[0] if emails else None
|
||
|
||
student, created = Student.objects.update_or_create(
|
||
student_id=student_id,
|
||
defaults={
|
||
'name': name,
|
||
'grade': grade,
|
||
'hope_admission_scheme': hope_admission_scheme,
|
||
'tuition_waiver': tuition_waiver,
|
||
'financial_assistance_disadvantaged_students': financial_assistance_disadvantaged_students,
|
||
'loan': loan,
|
||
'email': email
|
||
}
|
||
)
|
||
|
||
if created:
|
||
self.stdout.write(self.style.SUCCESS(f"Successfully added student: {student}"))
|
||
else:
|
||
self.stdout.write(self.style.WARNING(f"Updated existing student: {student}"))
|