Django get_or_create returns models.DoesNotExist when importing CSV

I spent quite some time to figure this out. I am just trying to import a CSV file using Python csv module and Django get_or_create ().

This is my simple code (built on this code):

import csv from .models import Person def import_data(): with open('/path/to/csv/people_list.csv') as f: reader = csv.reader(f) for row in reader: _, created = Org.objects.get_or_create( name=row[0], p_id=row[1], current_status=row[2], ) 

I get the following error when import_data () is run in the shell

 peoplelisting.models.DoesNotExist: Person matching query does not exist. 

Yes, this particular Person does not exist, but is the purpose of using get_or_create () really? If it does not exist, create it?

0
python django csv
Mar 30 '17 at 10:07 on
source share
2 answers

After a lot of conversation, it finally turned out that the problem is this:

My csv also contained a title bar that I did not ignore. I thought I would continue the meal and ignore the header only after I get the csv import to work, but the header itself was causing the problem (thanks to this , which (indirectly) helped a lot). The values ​​in the header do not match the schema (max_length, etc.), and this means that I had in mind Person matching query does not exist . Ignoring the header made it work. I just hope the error message was more visual. Hope this helps someone else save the hours I spent debugging a simple thing. Here is the correct code:

 import csv from .models import Person def import_data(): with open('/path/to/csv/people_list.csv') as f: reader = csv.reader(f) for row in reader: if row[0] != 'Person_name': #where Person_name is first column name _, created = Org.objects.get_or_create( name=row[0], p_id=row[1], current_status=row[2], ) 
0
Mar 30 '17 at 10:07 on
source share
β€” -

Instead of checking line [0] each time, you can simply skip the first line:

 next(reader, None) # skip the headers 

source: Skip headers when editing csv file using Python

0
Jul 16 '18 at 23:27
source share



All Articles