Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get_or_create returning models.DoesNotExist while importing a CSV

Tags:

python

csv

django

I have spent quite sometime to figure this out. I am simply trying to import a CSV file using Python's csv module and Django's get_or_create().

This is my simple code (built upon 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 = Person.objects.get_or_create(
                   name=row[0],
                   p_id=row[1],
                   current_status=row[2],
                   )

I get the following error when I run import_data() on the shell

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

Yes, this particular Person does not exist but isnt that the whole point of using get_or_create()? If it doesnt exist, create it?

like image 804
Anupam Avatar asked Oct 24 '25 20:10

Anupam


1 Answers

Instead of having to check row[0] every time, you could just skip the first row:

next(reader, None)  # skip the headers

source: Skip the headers when editing a csv file using Python

like image 81
Heidi Lyons Avatar answered Oct 26 '25 10:10

Heidi Lyons