添付されたcsvファイルを取得してdbに読み込むDjangoビューを作成しています:
ビュー.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()
これがかなり大雑把なコードであることは理解していますが、これを実行してフィールドの 1 つが空 ('') になると、ValueError could not convert string to float:
.
各フィールドでこれを行うことができます:
try:
report.mean_air_temp = float(line[4])
except(ValueError):
report.mean_air_temp = None
これにより、必要な結果が得られますが、それほど堅牢/エレガントではないようです。
このコード ブロックの処理方法に関するガイダンスをいただければ幸いです。