问题描述
我已经花了很多时间来弄清楚这一点。我只想使用Python的csv模块和Django的get_or_create()导入CSV文件。这是我的简单代码(建立在(间接)帮了很多)。标题中的值与模式(max_length等)不匹配,而且 Person匹配查询不存在
是指的。忽略标题使其工作。我只希望错误信息更具描述性。希望它有助于别人节省我花了很多时间来调试一个简单的事情。这是正确的代码:
import csv
from .models import Person
def import_data ():
with open('/ path / to / csv / people_list.csv')as f:
reader = csv.reader(f)
for reader in reader:
如果row [0]!='Person_name':#where Person_name是第一列的名称
_,created = Org.objects.get_or_create(
name = row [0],
p_id =行[1],
current_status =行[2],
)
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 = Org.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?
After a lot of playing around, finally figured the issue was the following:
My csv also contained a header row which I was not ignoring. I thought I'll proceed piece-meal and ignore the header only after I get the csv importing to work but the header itself was creating the problem (thanks to this post which (indirectly) helped a lot). The values in the header did not match the schema (max_length etc.) and thats what Person matching query does not exist
was referring to. Ignoring the header made it work. I just hope that the error message was more descriptive though. Hope it helps someone else save the hours I spent debugging a simple thing. Here's 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's name
_, created = Org.objects.get_or_create(
name=row[0],
p_id=row[1],
current_status=row[2],
)
这篇关于Django get_or_create返回models.DoesNotExist导入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!