Fixed #22889: Unneeded to_field in fk.deconstruct causing swap issues
This commit is contained in:
parent
0fba4c0ed7
commit
0b571753a8
|
@ -1673,7 +1673,8 @@ class ForeignKey(ForeignObject):
|
||||||
if self.rel.on_delete is not CASCADE:
|
if self.rel.on_delete is not CASCADE:
|
||||||
kwargs['on_delete'] = self.rel.on_delete
|
kwargs['on_delete'] = self.rel.on_delete
|
||||||
# Rel needs more work.
|
# Rel needs more work.
|
||||||
if self.rel.field_name:
|
to_meta = getattr(self.rel.to, "_meta", None)
|
||||||
|
if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
|
||||||
kwargs['to_field'] = self.rel.field_name
|
kwargs['to_field'] = self.rel.field_name
|
||||||
return name, path, args, kwargs
|
return name, path, args, kwargs
|
||||||
|
|
||||||
|
|
|
@ -169,7 +169,10 @@ class FieldDeconstructionTests(TestCase):
|
||||||
|
|
||||||
def test_foreign_key(self):
|
def test_foreign_key(self):
|
||||||
# Test basic pointing
|
# Test basic pointing
|
||||||
|
from django.contrib.auth.models import Permission
|
||||||
field = models.ForeignKey("auth.Permission")
|
field = models.ForeignKey("auth.Permission")
|
||||||
|
field.rel.to = Permission
|
||||||
|
field.rel.field_name = "id"
|
||||||
name, path, args, kwargs = field.deconstruct()
|
name, path, args, kwargs = field.deconstruct()
|
||||||
self.assertEqual(path, "django.db.models.ForeignKey")
|
self.assertEqual(path, "django.db.models.ForeignKey")
|
||||||
self.assertEqual(args, [])
|
self.assertEqual(args, [])
|
||||||
|
@ -194,6 +197,12 @@ class FieldDeconstructionTests(TestCase):
|
||||||
self.assertEqual(path, "django.db.models.ForeignKey")
|
self.assertEqual(path, "django.db.models.ForeignKey")
|
||||||
self.assertEqual(args, [])
|
self.assertEqual(args, [])
|
||||||
self.assertEqual(kwargs, {"to": "auth.User", "on_delete": models.SET_NULL})
|
self.assertEqual(kwargs, {"to": "auth.User", "on_delete": models.SET_NULL})
|
||||||
|
# Test to_field preservation
|
||||||
|
field = models.ForeignKey("auth.Permission", to_field="foobar")
|
||||||
|
name, path, args, kwargs = field.deconstruct()
|
||||||
|
self.assertEqual(path, "django.db.models.ForeignKey")
|
||||||
|
self.assertEqual(args, [])
|
||||||
|
self.assertEqual(kwargs, {"to": "auth.Permission", "to_field": "foobar"})
|
||||||
|
|
||||||
@override_settings(AUTH_USER_MODEL="auth.Permission")
|
@override_settings(AUTH_USER_MODEL="auth.Permission")
|
||||||
def test_foreign_key_swapped(self):
|
def test_foreign_key_swapped(self):
|
||||||
|
|
Loading…
Reference in New Issue