1
我寫一個Django視圖這需要附加的CSV文件,並讀入數據庫:Django的閱讀上傳CSV文件有一些空字段
views.py:
def climate_upload(request):
...
if form.is_valid(): # All validation rules pass
file = request.FILES['attach']
for line in file:
line = line.split(';')
report = Site1()
...
# These fields values be empty, integer or float
report.mean_air_temp = float(line[4])
report.min_air_temp = float(line[5])
report.max_air_temp = float(line[6])
report.sea_temp = float(line[7])
report.mean_rel_hum = float(line[8])
report.precipitation = float(line[9])
report.save()
file.close()
我明白這是非常粗略的代碼,但如果我運行這個和其中一個字段是空的(''),我得到一個ValueError could not convert string to float:
。
我可以爲每個字段做:
try:
report.mean_air_temp = float(line[4])
except(ValueError):
report.mean_air_temp = None
這給了我所要求的結果,但似乎並沒有如此強勁/優雅。
我將不勝感激關於如何處理這個代碼塊的任何指導。
後者可能不會產生在事件所要求的輸出,該文件中的號爲0。 –
正確你,更新它 – John
級長。我使用第二種方法。謝謝。 –