diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index 828200c..6833b6d 100644
a
|
b
|
class ForeignKey(RelatedField, Field):
|
743 | 743 | super(ForeignKey, self).validate(value, model_instance) |
744 | 744 | if not value: |
745 | 745 | return |
746 | | try: |
747 | | self.rel.to._default_manager.get(**{self.rel.field_name:value}) |
748 | | except self.rel.to.DoesNotExist, e: |
| 746 | |
| 747 | if not self.rel.to._default_manager.filter(**{self.rel.field_name:value}).complex_filter(self.rel.limit_choices_to).exists(): |
749 | 748 | raise exceptions.ValidationError( |
750 | 749 | self.error_messages['invalid'] % {'model': self.rel.to._meta.verbose_name, 'pk': value}) |
751 | 750 | |
diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
index f1b0c51..9813be7 100644
a
|
b
|
class ModelToValidate(models.Model):
|
12 | 12 | name = models.CharField(max_length=100) |
13 | 13 | created = models.DateTimeField(default=datetime.now) |
14 | 14 | number = models.IntegerField() |
15 | | parent = models.ForeignKey('self', blank=True, null=True) |
| 15 | parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'name__startswith': 'Some'}) |
16 | 16 | email = models.EmailField(blank=True) |
17 | 17 | url = models.URLField(blank=True) |
18 | 18 | f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answer_to_universe]) |
diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py
index c00070b..1ec574c 100644
a
|
b
|
class BaseModelValidationTests(ValidationTestCase):
|
32 | 32 | mtv=ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) |
33 | 33 | self.assertEqual(None, mtv.full_validate()) |
34 | 34 | |
| 35 | def test_limitted_FK_raises_error(self): |
| 36 | parent = ModelToValidate.objects.create(number=10, name='Other Name') |
| 37 | mtv=ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) |
| 38 | self.assertFailsValidation(mtv.full_validate, ['parent']) |
| 39 | |
35 | 40 | def test_wrong_email_value_raises_error(self): |
36 | 41 | mtv = ModelToValidate(number=10, name='Some Name', email='not-an-email') |
37 | 42 | self.assertFailsValidation(mtv.full_validate, ['email']) |