简体   繁体   English

Django模型输入的所有字段以逗号分隔

[英]All Fields of Django Model Entry Comma Separated

The code in the two if-blocks smells to violate DRY. 两个if块中的代码闻起来违反了DRY。 How can it be written more generic? 如何写得更通用?

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')

I could write in each model (Treatment and Patient) a method 'make_csv'. 我可以在每个模型(治疗和患者)中编写一个方法“ make_csv”。 But, there must be a better way. 但是,必须有更好的方法。

A simple solution: 一个简单的解决方案:

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))

Or, if you want a slightly more complex solution that avoids repeating the if : 或者,如果您想要一个稍微复杂一点的解决方案,避免重复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))

It's also more flexible in case you may want to change or add options to choices_dict , but that may not be relevant. 如果您可能想要更改或添加选项到choices_dict ,它也更加灵活,但这可能并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM