diff --git a/django/forms/models.py b/django/forms/models.py
index 6024a1c..6e043ff 100644
a
|
b
|
class ModelMultipleChoiceField(ModelChoiceField):
|
664 | 664 | |
665 | 665 | def __init__(self, queryset, cache_choices=False, required=True, |
666 | 666 | widget=None, label=None, initial=None, |
667 | | help_text=None, *args, **kwargs): |
| 667 | help_text=None, to_field_name=None, *args, **kwargs): |
668 | 668 | super(ModelMultipleChoiceField, self).__init__(queryset, None, |
669 | 669 | cache_choices, required, widget, label, initial, help_text, |
670 | | *args, **kwargs) |
| 670 | to_field_name, *args, **kwargs) |
671 | 671 | |
672 | 672 | def clean(self, value): |
673 | 673 | if self.required and not value: |
… |
… |
class ModelMultipleChoiceField(ModelChoiceField):
|
679 | 679 | final_values = [] |
680 | 680 | for val in value: |
681 | 681 | try: |
682 | | obj = self.queryset.get(pk=val) |
| 682 | key = self.to_field_name or 'pk' |
| 683 | obj = self.queryset.get(**{key: val}) |
683 | 684 | except self.queryset.model.DoesNotExist: |
684 | 685 | raise ValidationError(self.error_messages['invalid_choice'] % val) |
685 | 686 | else: |
diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
index e3821de..21a1a33 100644
a
|
b
|
ValidationError: [u'Select a valid choice. z is not one of the available choices
|
1232 | 1232 | (86, u'Apple') |
1233 | 1233 | (22, u'Pear') |
1234 | 1234 | (87, u'Core') |
| 1235 | >>> field.clean(u'87') |
| 1236 | <Inventory: Core> |
| 1237 | |
| 1238 | >>> field = ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') |
| 1239 | >>> for choice in field.choices: |
| 1240 | ... print choice |
| 1241 | (86, u'Apple') |
| 1242 | (22, u'Pear') |
| 1243 | (87, u'Core') |
| 1244 | >>> field.clean([u'86',u'22']) |
| 1245 | [<Inventory: Apple>, <Inventory: Pear>] |
1235 | 1246 | |
1236 | 1247 | >>> class InventoryForm(ModelForm): |
1237 | 1248 | ... class Meta: |