I have a simple yet frustrating problem that I can't seem to figure out.
I'm trying to load data from a csv file into a Django model. To do so I've written the following script as a view:
import csv
def import_db(request):
dataReader = csv.reader(open('/home/<name>/webapps/<name2>/employees.csv'), delimiter=',', quotechar='"')
for row in dataReader:
emp = Employee()
emp.first_name = row[0]
emp.last_name = row[1]
emp.email = row[2]
emp.level = row[3]
emp.service_area = row[4]
emp.service_line = row[5]
emp.office = row[6]
emp.save()
return HttpResponse("Completed", content_type="text/plain")
I've linked the view to a url as follows:
from reviews import views as emp
url(r'^load/$', emp.import_db, name='importdb')
The idea being that when I go to the link sitename.com/load, my data will get loaded from my employee.csv file into my Employee model.
The problem is when I run this script, I get 2 entries in my Django model for every line in my csv file. I have 1530 employee lines in the csv and the model gets populated with 3060 instances when I do this. What's even more annoying is that the order of the entries in the model is not the same as the csv file so I can't simply delete the second 'group' of 1530 model instances. Even when I try it with a subset of 20 lines of data in the csv file I get 40 model instances. Any idea why this is happening and what i can do to fix it?
Thanks a lot!