让这段代码将csv导入我的Django DB。 这是我的模型数据库,在保存时我得到了错误。这是创建错误的行
23764,"HUA FU","vessel","DPRK4",-0- ,-0- ,-0- ,"10,030",-0- ,"Panama",-0- ,"Vessel Registration Identification IMO 9020003; Linked To: CHANG AN SHIPPING & TECHNOLOGY."
在我的数据库中,该列为vessel_dwt = models.IntegerField(blank=True, null=True)
我应该如何将列放入数据库?作为浮点数还是字符串?这是我的导入代码。
import csv, sys, os
# project_dir = "/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/import_save/"
# project_dir = "/Users/Dropbox/ofac_project/ofac_sdn/import_save/"
project_dir = "/Users/Dropbox/ofac_project"
sys.path.append(project_dir)
os.environ['DJANGO_SETTINGS_MODULE']='ofac.settings'
import django
django.setup()
from ofac_sdn.models import Ofac_Sdn
from ofac_sdn.models import Ofac_Add
from ofac_sdn.models import Ofac_Alt
from ofac_sdn.models import Ofac_Sdn_Comments
file = 'new_sdn.csv'
file1 = 'new_add.csv'
file2 ='new_alt.csv'
file3 ='new_sdn_comments.csv'
data = csv.reader(open(file),delimiter=",")
for row in data:
if row[0] !="Number":
post = Ofac_Sdn()
post.number = row[0]
post.name = row[1]
post.b_i=row[2]
post.programe=row[3]
post.more_info=row[4]
post.vessel_call_sign=row[5]
post.vessel_type=row[6]
post.vessel_dwt=row[7]
post.tonnage=row[8]
post.vessel_flag=row[9]
post.vessel_owner=row[10]
post.dob_aka=row[11]
post.save()
在导入之前,我将替换奇数字符:
import requests
import csv, os, sys
newstring = "null"
newinteger = str(0)
newstring1= "null"
newstring2= "null"
newstring3= "null"
with open('sdn.csv', 'r') as file1, open('new_sdn.csv', 'w') as file2:
reader = csv.reader(file1, delimiter=',')
writer = csv.writer(file2, delimiter=',')
for row in reader:
replaced7 = row[7].replace('-0-', newinteger)
row[7] = replaced7
writer.writerow(row)
谢谢!
答案 0 :(得分:1)
我已经从田里删除了所有的昏迷。
我已添加此代码:
replaced7b=row[7].replace(',', '')
row[7]=replaced7b
replaced8 = row[8].replace('-0-', newinteger)
row[8]=replaced8
replaced8b=row[8].replace(',', '')
row[8]=replaced8b
答案 1 :(得分:0)
你可以使用这样一个班轮。
post.vessel_dwt=int(''.join(row[7].split(',')))