Reputation: 5562
New to Django/Python. I need to write an import script for a CSV file to seed some data (not using fixtures, did that already as that is JSON based and not CSV).
This works:
import csv
from datetime import datetime
from django.utils.timezone import make_aware
from django.core.management.base import BaseCommand
from chatterbox.models import Organisation, Course, Student
class Command(BaseCommand):
def handle(self, **options):
CSV_PATH = './students_AEKI.csv'
Student.objects.filter(organisation__name__exact="AEKI").delete()
with open(CSV_PATH) as file:
file.readline() # skip the header
csv_reader = csv.reader(file, delimiter=',')
org = Organisation.objects.filter(name="AEKI")
for row in csv_reader:
_, Student.objects.get_or_create(
first_name=row[0],
last_name=row[1],
email=row[2],
organisation=org[0],
enrolled=row[4],
last_booking=row[5],
credits_total=row[6],
credits_balance=row[7],
)
This does NOT work:
import csv
from datetime import datetime
from django.utils.timezone import make_aware
from django.core.management.base import BaseCommand
from chatterbox.models import Organisation, Course, Student
class Command(BaseCommand):
def handle(self, **options):
CSV_PATH = './students_AEKI.csv'
Student.objects.filter(organisation__name__exact="AEKI").delete()
with open(CSV_PATH) as file:
file.readline() # skip the header
csv_reader = csv.reader(file, delimiter=',')
org = Organisation.objects.filter(name="AEKI")
for row in csv_reader:
enrolled_utc = make_aware(datetime.strptime(row[4], '%Y-%m-%d'))
last_booking_utc = make_aware(datetime.strptime((row[5], '%Y-%m-%d'))
_, Student.objects.get_or_create(
first_name=row[0],
last_name=row[1],
email=row[2],
organisation=org[0],
enrolled=enrolled_utc,
last_booking=last_booking_utc,
credits_total=row[6],
credits_balance=row[7],
)
Syntax error at the "_".
I need to do some manipulation (eg like adding timezone to date fields) on data before creating it in the table. So what is wrong with the 2nd version?
Upvotes: 0
Views: 140
Reputation: 3531
There's a Syntax error at the "_". Remove the trailing characters.
Also this line has an extra bracket:
last_booking_utc = datetime.strptime((row[5], '%Y-%m-%d')
From
for row in csv_reader:
enrolled_utc = make_aware(datetime.strptime(row[4], '%Y-%m-%d'))
last_booking_utc = make_aware(datetime.strptime((row[5], '%Y-%m-%d'))
_, Student.objects.get_or_create(
first_name=row[0],
last_name=row[1],
email=row[2],
organisation=org[0],
enrolled=enrolled_utc,
last_booking=last_booking_utc,
credits_total=row[6],
credits_balance=row[7],
)
To
for row in csv_reader:
enrolled_utc = make_aware(datetime.strptime(row[4], '%Y-%m-%d'))
last_booking_utc = make_aware(datetime.strptime(row[5], '%Y-%m-%d'))
Student.objects.get_or_create(
first_name=row[0],
last_name=row[1],
email=row[2],
organisation=org[0],
enrolled=enrolled_utc,
last_booking=last_booking_utc,
credits_total=row[6],
credits_balance=row[7],
)
Upvotes: 1