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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With