I wanted some guidance if possible on how to make this more generic:
def get_industry_choices(self):
industries = Industry.objects.all().order_by('name')
ind_arr = [(ind.id, ind.name) for ind in industries]
return ind_arr
Basically this function will return choices
as expected for the forms.ChoiceField
. I need to do this in a few places, and wanted to make the function above more generic. I know how to get the industries = Industry.objects.all().order_by('name')
to be generic, but the 2nd part is what I'm not sure about. When creating the tuples, it has (ind.id, ind.name)
. the ind.name
can be any value depending on the model passed in (it may not always have name
in the model).
I tried to read up on this in a few places including:
Passing functions with arguments to another function in Python?
The above resource shows how to do it using a function passed in, but that seems a bit overkill? If I have to pass a function as an argument anyway, whats the point of making it more generic with one more function?
[EDIT]
Basically I want to produce something similar to this:
TITLE_CHOICES=(
(1, 'Mr.'),
(2, 'Ms.'),
(3, 'Mrs.'),
(4, 'Dr.'),
(5, 'Prof.'),
(6, 'Rev.'),
(7, 'Other'),
)
So when doing forms.ChoiceField
I can pass in TITLE_CHOICES
for example as the possible choices. The first value is the value I get when the form is submitted, the second value is what the user sees on form. I want to be able to programmatically create this with any model, I pass in the model name and one field in the above example, name
. I want to create the tuple such that it is (id, name)
. But name
could be replaced with anything in a different model...