Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #6445 -- Allow model instances to be used as a default for Fore…

…ignKeys

(via a callable). Also updates the documentation of the "default" attribute to
indicate a callable can be used. Thanks, Philipe Raoult.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@7331 bcc190cf-cafb-0310-a4f2-bffc1f526a37
commit b3b8422363dd450d1ff1a376ab1f74cf2e22ce1b 1 parent 597f9d6
Malcolm Tredinnick malcolmt authored
7 django/db/models/fields/related.py
View
@@ -548,6 +548,13 @@ def prepare_field_objs_and_params(self, manipulator, name_prefix):
params['choices'] = self.get_choices_default()
return field_objs, params
+ def get_default(self):
+ "Here we check if the default value is an object and return the to_field if so."
+ field_default = super(ForeignKey, self).get_default()
+ if isinstance(field_default, self.rel.to):
+ return getattr(field_default, self.rel.get_related_field().attname)
+ return field_default
+
def get_manipulator_field_objs(self):
rel_field = self.rel.get_related_field()
if self.rel.raw_id_admin and not isinstance(rel_field, AutoField):
3  docs/model-api.txt
View
@@ -626,7 +626,8 @@ option is ignored.
``default``
~~~~~~~~~~~
-The default value for the field.
+The default value for the field. This can be a value or a callable object. If
+callable it will be called every time a new object is created.
``editable``
~~~~~~~~~~~~
24 tests/regressiontests/model_fields/models.py
View
@@ -0,0 +1,24 @@
+
+from django.db import models
+
+class Foo(models.Model):
+ a = models.CharField(max_length=10)
+
+def get_foo():
+ return Foo.objects.get(id=1)
+
+class Bar(models.Model):
+ b = models.CharField(max_length=10)
+ a = models.ForeignKey(Foo, default=get_foo)
+
+__test__ = {'API_TESTS':"""
+# Create a couple of Places.
+>>> f = Foo.objects.create(a='abc')
+>>> f.id
+1
+>>> b = Bar(b = "bcd")
+>>> b.a
+<Foo: Foo object>
+>>> b.save()
+
+"""}
Please sign in to comment.
Something went wrong with that request. Please try again.