python - All Fields of Django Model Entry Comma Separated -


the code in 2 if-blocks smells violate dry. how can written more generic?

selected_class = eval(choice)            # bad  (see comments) selected_class = getattr(models, choice) # (see comments) records = selected_class.objects.all() if (choice == 'treatment'):     record in records:         response.write(str(record.id) + ',' + str(record.available_hours) + '\n') if (choice == 'patient'):     record in records:         response.write(str(record.id) + ',' + record.first_name + '\n') 

i write in each model (treatment , patient) method 'make_csv'. but, there must 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 want more complex solution avoids repeating if:

choices_dict = {     'treatment': 'available_hours',     'patient': 'first_name', }  record_field = choices_dict[choice]  record in records:     item = getattr(record, record_field)      response.write('{},{}\n'.format(record.id, item)) 

it's more flexible in case may want change or add options choices_dict, may not relevant.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -