问题
I am using django 1.7.2 and I have been given some code for a choices list to be placed in a model.
Here is the code:
YOB_TYPES = Choices(*(
((0, 'select_yob', _(' Select Year of Birth')),
(2000, 'to_present', _('2000 to Present'))) +
tuple((i, str(i)) for i in xrange(1990, 2000)) +
(1, 'unspecified', _('Prefer not to answer')))
)
....
year_of_birth_type = models.PositiveIntegerField(choices=YOB_TYPES, default=YOB_TYPES.select_yob, validators=[MinValueValidator(1)])
....
The above code gives the incorrect select list as shown below. I have read several SO posts & google searches and scoured the docs, but I am stuck and I am going around in circles.
This is how the current code displays the select list, which is wrong:

However, I want the select list to be displayed as follows:

回答1:
You should wrap the last tuple in another tuple:
YOB_TYPES = Choices(*(
((0, 'select_yob', _(' Select Year of Birth')),
(2000, 'to_present', _('2000 to Present'))) +
tuple((i, str(i)) for i in xrange(1990, 2000)) +
((1, 'unspecified', _('Prefer not to answer')),))
)
回答2:
1) You have to be careful when adding up tuples - you need to set a comma at the end so that python interprets this as a tuple:
YOB_TYPES = Choices(*(
((0, 'select_yob', _(' Select Year of Birth')),
(2000, 'to_present', _('2000 to Present'))) +
tuple((i, str(i)) for i in xrange(1990, 2000)) +
((1, 'unspecified', _('Prefer not to answer')),))
)
2) You have to order your choices according you want them to appear in the list - so the "2000 to present" should move one place to the back.
3) It would make more sense to use the empty_label attribute - and to remove the first item of your choices:
empty_label="(Select Year fo Birth)"
来源:https://stackoverflow.com/questions/29227302/django-models-choices-list