diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index 5de6fb1..b217791 100644
a
|
b
|
class ForeignKey(RelatedField, Field):
|
789 | 789 | if not value: |
790 | 790 | return |
791 | 791 | |
792 | | qs = self.rel.to._default_manager.filter(**{self.rel.field_name:value}) |
| 792 | db = model_instance._state.db |
| 793 | if db is None: |
| 794 | db = router.db_for_write(model_instance.__class__, instance=model_instance) |
| 795 | qs = self.rel.to._default_manager.using(db).filter(**{self.rel.field_name:value}) |
793 | 796 | qs = qs.complex_filter(self.rel.limit_choices_to) |
794 | 797 | if not qs.exists(): |
795 | 798 | raise exceptions.ValidationError(self.error_messages['invalid'] % { |
diff --git a/tests/regressiontests/multiple_database/tests.py b/tests/regressiontests/multiple_database/tests.py
index fd6e644..5dbec99 100644
a
|
b
|
class QueryTestCase(TestCase):
|
64 | 64 | title="Dive into Python" |
65 | 65 | ) |
66 | 66 | |
| 67 | def test_foreign_key_validation(self): |
| 68 | """ |
| 69 | ForeignKey validation when both object and related object were created |
| 70 | on another database wouldn't try to look up related object on the default database |
| 71 | """ |
| 72 | # Create a book on the second database |
| 73 | george = Person.objects.using('other').create(name="George Vilches") |
| 74 | book = Book.objects.using('other').create(title="Pro Django", |
| 75 | published=datetime.date(2008, 12, 16), |
| 76 | editor=george) |
| 77 | |
| 78 | #if validation fails full_clean raises ValidationError |
| 79 | self.assertEqual(book.full_clean(), None) |
67 | 80 | |
68 | 81 | def test_other_creation(self): |
69 | 82 | "Objects created on another database don't leak onto the default database" |