将数据从csv
文件存储到数据库时,出现错误:
ValueError at /assignment/get/
Field 'zip' expected a number but got 'zip'
model.py
from django.db import model
class csvData(models.Model):
zip=models.IntegerField()
lat=models.IntegerField()
lng=models.IntegerField()
views.py
import csv
from .models import csvData
def get(request):
fname="uszips.csv"
with open(fname) as csvfile:
csv_reader=csv.reader(csvfile, delimiter=',')
for row in csv_reader:
csvdata=csvData()
csvdata.zip=row[0]
csvdata.lat=row[1]
csvdata.lng=row[2]
答案 0 :(得分:0)
第一行可能是标题,因此是列的名称。 尝试跳过第一行。
此外,您还需要将这些值转换为整数,因为它们都是字符串。
也许是这样的:
def get(request):
...
with open(fname) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for i, row in enumerate(csv_reader):
if i == 0:
# skip first row
continue
csvdata = csvData()
csvdata.zip = int(row[0])
csvdata.lat = int(row[1])
csvdata.lng = int(row[2])
...