diff options
| author | Brian Rosner <brosner@gmail.com> | 2008-09-01 22:43:38 +0000 |
|---|---|---|
| committer | Brian Rosner <brosner@gmail.com> | 2008-09-01 22:43:38 +0000 |
| commit | ce47d4ab830bb96fe9325b9ccd077619116fd548 (patch) | |
| tree | 6e061d6596a3d0155db45b6a06f28d2cc0b1d4cc /django/forms | |
| parent | dcb0e8f959148331cde89def02ce28be3b248039 (diff) | |
Fixed #8648 -- Admin no longer ignores to_field. Thanks for the help Karen Tracey and SmileyChris.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8823 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/forms')
| -rw-r--r-- | django/forms/models.py | 19 |
1 files changed, 14 insertions, 5 deletions
diff --git a/django/forms/models.py b/django/forms/models.py index 8e59ebecda..56e7f2aabd 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -550,14 +550,21 @@ class ModelChoiceIterator(object): if self.field.cache_choices: if self.field.choice_cache is None: self.field.choice_cache = [ - (obj.pk, self.field.label_from_instance(obj)) - for obj in self.queryset.all() + self.choice(obj) for obj in self.queryset.all() ] for choice in self.field.choice_cache: yield choice else: for obj in self.queryset.all(): - yield (obj.pk, self.field.label_from_instance(obj)) + yield self.choice(obj) + + def choice(self, obj): + if self.field.to_field_name: + key = getattr(obj, self.field.to_field_name) + else: + key = obj.pk + return (key, self.field.label_from_instance(obj)) + class ModelChoiceField(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" @@ -570,7 +577,7 @@ class ModelChoiceField(ChoiceField): def __init__(self, queryset, empty_label=u"---------", cache_choices=False, required=True, widget=None, label=None, initial=None, - help_text=None, *args, **kwargs): + help_text=None, to_field_name=None, *args, **kwargs): self.empty_label = empty_label self.cache_choices = cache_choices @@ -580,6 +587,7 @@ class ModelChoiceField(ChoiceField): *args, **kwargs) self.queryset = queryset self.choice_cache = None + self.to_field_name = to_field_name def _get_queryset(self): return self._queryset @@ -622,7 +630,8 @@ class ModelChoiceField(ChoiceField): if value in EMPTY_VALUES: return None try: - value = self.queryset.get(pk=value) + key = self.to_field_name or 'pk' + value = self.queryset.get(**{key: value}) except self.queryset.model.DoesNotExist: raise ValidationError(self.error_messages['invalid_choice']) return value |
