在将数据从csv
文件存储到数据库时,我收到错误:
ValueError at /assignment/get/
Field 'zip' expected a number but got 'zip'
型号.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]
第一行可能是标题,所以列的名称。试着跳过第一行。
此外,您需要将值转换为整数,因为它们都将是字符串。
可能是这样的:
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])
...