diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 6d3176512c..7243276305 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -220,6 +220,10 @@ Note that ``lambda``\s cannot be used for field options like ``default`` because they cannot be :ref:`serialized by migrations `. See that documentation for other caveats. +For fields like :class:`ForeignKey` that map to model instances, defaults +should be the value of the field they reference (``pk`` unless +:attr:`~ForeignKey.to_field` is set) instead of model instances. + The default value is used when new model instances are created and a value isn't provided for the field. When the field is a primary key, the default is also used when the field is set to ``None``. diff --git a/tests/delete/models.py b/tests/delete/models.py index 38e7c7cf0e..3255c68c64 100644 --- a/tests/delete/models.py +++ b/tests/delete/models.py @@ -13,7 +13,7 @@ class R(models.Model): def get_default_r(): - return R.objects.get_or_create(is_default=True)[0] + return R.objects.get_or_create(is_default=True)[0].pk class S(models.Model): diff --git a/tests/delete/tests.py b/tests/delete/tests.py index 11e780bfac..60c61ed281 100644 --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -31,7 +31,7 @@ class OnDeleteTests(TestCase): a = create_a('setvalue') a.setvalue.delete() a = A.objects.get(pk=a.pk) - self.assertEqual(self.DEFAULT, a.setvalue) + self.assertEqual(self.DEFAULT, a.setvalue.pk) def test_setnull(self): a = create_a('setnull') @@ -43,7 +43,7 @@ class OnDeleteTests(TestCase): a = create_a('setdefault') a.setdefault.delete() a = A.objects.get(pk=a.pk) - self.assertEqual(self.DEFAULT, a.setdefault) + self.assertEqual(self.DEFAULT, a.setdefault.pk) def test_setdefault_none(self): a = create_a('setdefault_none') diff --git a/tests/forms_tests/models.py b/tests/forms_tests/models.py index 7eb4792213..d7e9d583ff 100644 --- a/tests/forms_tests/models.py +++ b/tests/forms_tests/models.py @@ -72,7 +72,7 @@ class ChoiceOptionModel(models.Model): def choice_default(): - return ChoiceOptionModel.objects.get_or_create(name='default')[0] + return ChoiceOptionModel.objects.get_or_create(name='default')[0].pk def choice_default_list(): diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py index 931468c9bf..a836cbb97e 100644 --- a/tests/model_fields/models.py +++ b/tests/model_fields/models.py @@ -26,7 +26,7 @@ class Foo(models.Model): def get_foo(): - return Foo.objects.get(id=1) + return Foo.objects.get(id=1).pk class Bar(models.Model):