Skip to content

Commit dec93d8

Browse files
kmtraceytimgraham
authored andcommitted
Fixed #21612 -- Made QuerySet.update() respect to_field
1 parent de91249 commit dec93d8

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

django/db/models/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -826,10 +826,10 @@ def _get_next_or_previous_in_order(self, is_next):
826826
setattr(self, cachename, obj)
827827
return getattr(self, cachename)
828828

829-
def prepare_database_save(self, unused):
829+
def prepare_database_save(self, field):
830830
if self.pk is None:
831831
raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
832-
return self.pk
832+
return getattr(self, field.rel.field_name)
833833

834834
def clean(self):
835835
"""

tests/update/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,11 @@ class C(models.Model):
4242

4343
class D(C):
4444
a = models.ForeignKey(A)
45+
46+
47+
class Foo(models.Model):
48+
target = models.CharField(max_length=10, unique=True)
49+
50+
51+
class Bar(models.Model):
52+
foo = models.ForeignKey(Foo, to_field='target')

tests/update/tests.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from django.test import TestCase
44

5-
from .models import A, B, D, DataPoint, RelatedPoint
5+
from .models import A, B, D, DataPoint, RelatedPoint, Foo, Bar
66

77

88
class SimpleTest(TestCase):
@@ -125,3 +125,16 @@ def test_update_slice_fail(self):
125125
method = DataPoint.objects.all()[:2].update
126126
self.assertRaises(AssertionError, method,
127127
another_value='another thing')
128+
129+
def test_update_respects_to_field(self):
130+
"""
131+
Update of an FK field which specifies a to_field works.
132+
"""
133+
a_foo = Foo.objects.create(target='aaa')
134+
b_foo = Foo.objects.create(target='bbb')
135+
bar = Bar.objects.create(foo=a_foo)
136+
self.assertEqual(bar.foo_id, a_foo.target)
137+
bar_qs = Bar.objects.filter(pk=bar.pk)
138+
self.assertEqual(bar_qs[0].foo_id, a_foo.target)
139+
bar_qs.update(foo=b_foo)
140+
self.assertEqual(bar_qs[0].foo_id, b_foo.target)

0 commit comments

Comments
 (0)