两个if-blocks中的代码有时会违反DRY。如何写得更通用?
selected_class = eval(choice) # bad (see comments)
selected_class = getattr(models, choice) # good (see comments)
records = selected_class.objects.all()
if (choice == 'Treatment'):
for record in records:
response.write(str(record.id) + ',' + str(record.available_hours) + '\n')
if (choice == 'Patient'):
for record in records:
response.write(str(record.id) + ',' + record.first_name + '\n')
我可以在每个模型(治疗和患者)中写一个方法'make_csv'。但是,必须有更好的方法。
答案 0 :(得分:1)
一个简单的解决方案:
for record in records:
if choice == 'Treatment':
item = str(record.available_hours)
elif choice == 'Patient':
item = record.first_name
response.write('{},{}\n'.format(record.id, item))
或者,如果您想要一个稍微复杂的解决方案,以避免重复if
:
choices_dict = {
'Treatment': 'available_hours',
'Patient': 'first_name',
}
record_field = choices_dict[choice]
for record in records:
item = getattr(record, record_field)
response.write('{},{}\n'.format(record.id, item))
如果您想要更改或添加choices_dict
的选项,它也会更灵活,但这可能不相关。