diff --git a/django/db/models/base.py b/django/db/models/base.py index f2404d40a5c..2b79a20cee2 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -826,10 +826,10 @@ class Model(six.with_metaclass(ModelBase)): setattr(self, cachename, obj) return getattr(self, cachename) - def prepare_database_save(self, unused): + def prepare_database_save(self, field): if self.pk is None: raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self) - return self.pk + return getattr(self, field.rel.field_name) def clean(self): """ diff --git a/tests/update/models.py b/tests/update/models.py index ebc9c3353c9..e0b391d0cdf 100644 --- a/tests/update/models.py +++ b/tests/update/models.py @@ -42,3 +42,11 @@ class C(models.Model): class D(C): a = models.ForeignKey(A) + + +class Foo(models.Model): + target = models.CharField(max_length=10, unique=True) + + +class Bar(models.Model): + foo = models.ForeignKey(Foo, to_field='target') diff --git a/tests/update/tests.py b/tests/update/tests.py index 95e9069972f..578b3ab4402 100644 --- a/tests/update/tests.py +++ b/tests/update/tests.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals from django.test import TestCase -from .models import A, B, D, DataPoint, RelatedPoint +from .models import A, B, D, DataPoint, RelatedPoint, Foo, Bar class SimpleTest(TestCase): @@ -125,3 +125,16 @@ class AdvancedTests(TestCase): method = DataPoint.objects.all()[:2].update self.assertRaises(AssertionError, method, another_value='another thing') + + def test_update_respects_to_field(self): + """ + Update of an FK field which specifies a to_field works. + """ + a_foo = Foo.objects.create(target='aaa') + b_foo = Foo.objects.create(target='bbb') + bar = Bar.objects.create(foo=a_foo) + self.assertEqual(bar.foo_id, a_foo.target) + bar_qs = Bar.objects.filter(pk=bar.pk) + self.assertEqual(bar_qs[0].foo_id, a_foo.target) + bar_qs.update(foo=b_foo) + self.assertEqual(bar_qs[0].foo_id, b_foo.target)