diff options
| -rw-r--r-- | django/db/models/fields/__init__.py | 39 |
1 files changed, 17 insertions, 22 deletions
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index b2e9b18351..4a006bc85d 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -3,6 +3,7 @@ import copy import datetime import decimal import itertools +import operator import uuid import warnings from base64 import b64decode, b64encode @@ -790,31 +791,25 @@ class Field(RegisterLookupMixin): Return choices with a default blank choices included, for use as <select> choices for this field. """ - blank_defined = False - choices = list(self.choices) if self.choices else [] - named_groups = choices and isinstance(choices[0][1], (list, tuple)) - if not named_groups: - for choice, __ in choices: - if choice in ('', None): - blank_defined = True - break - - first_choice = (blank_choice if include_blank and - not blank_defined else []) if self.choices: - return first_choice + choices + choices = list(self.choices) + if include_blank: + named_groups = isinstance(choices[0][1], (list, tuple)) + blank_defined = not named_groups and any(choice in ('', None) for choice, __ in choices) + if not blank_defined: + choices = blank_choice + choices + return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() - if hasattr(self.remote_field, 'get_related_field'): - lst = [(getattr(x, self.remote_field.get_related_field().attname), - smart_text(x)) - for x in rel_model._default_manager.complex_filter( - limit_choices_to)] - else: - lst = [(x.pk, smart_text(x)) - for x in rel_model._default_manager.complex_filter( - limit_choices_to)] - return first_choice + lst + choice_func = operator.attrgetter( + self.remote_field.get_related_field().attname + if hasattr(self.remote_field, 'get_related_field') + else 'pk' + ) + return (blank_choice if include_blank else []) + [ + (choice_func(x), smart_text(x)) + for x in rel_model._default_manager.complex_filter(limit_choices_to) + ] def value_to_string(self, obj): """ |
