Simplified Field.get_choices().

This commit is contained in:
Sergey Fedoseev 2017-11-12 05:38:29 +05:00 committed by Tim Graham
parent f152678d36
commit bdb747a5f2
1 changed files with 17 additions and 22 deletions

View File

@ -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):
"""