我觉得这个序列可能写得更短:
dim = Dimension.objects.get(pk=rows['pk'])
try:
dim.name = rows['name']
except KeyError:
pass
try:
dim.external_flg = rows['external_flg']
except:
pass
try:
dim.ext_owner = rows['ext_owner']
except KeyError:
pass
try:
dim.ext_table_name = rows['ext_table_name']
except KeyError:
pass
try:
dim.ext_start_date_column_name = rows['ext_start_date_column_name']
except KeyError:
pass
try:
dim.ext_end_date_column_name = rows['ext_end_date_column_name']
except KeyError:
pass
我从未有过使用Python代码优化和处理异常的经验,但我很高兴有一个替代示例如何缩短它。
谢谢!
答案 0 :(得分:4)
使用dict.get()
方法:
dim.name = rows.get('name', dim.name)
或者,对于更多DRY解决方案,将所有分配放入循环:
for field_name in ('name', 'external_flg', 'ext_owner', 'ext_table_name',
'ext_start_date_column_name', 'ext_end_date_column_name'):
if field_name in rows:
setattr(dim, field_name, rows[field_name])
要处理list
数据,您可以进行类似的循环:
for i, field_name in enumerate(('name', 'external_flg', 'ext_owner',
'ext_table_name', 'ext_start_date_column_name',
'ext_end_date_column_name')):
if i < len[rows]:
setattr(dim, field_name, rows[i])
答案 1 :(得分:3)
这样的东西应该有用 - 这个答案包括try / catch块来捕获KeyError: - )
attributes = ['name', 'external_flg', 'ext_owner', 'ext_table_name',
'ext_start_date_column_name', 'ext_end_date_column_name']
dim = Dimension.objects.get(pk=rows['pk'])
for attr in attributes:
try:
setattr(dim, attr, rows[attr])
except KeyError:
pass