summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2008-12-08 08:23:52 +0000
committerMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2008-12-08 08:23:52 +0000
commitbffb45786297b11e6f189c302d084afca670709a (patch)
tree4847194b63aef36f2edecfe5ff255c92f533ccc1
parent85e1d876c0ca7967452dc8e66ce4dc14b55dea85 (diff)
[1.0.X] The first step in fixing a group of problems related to outputting a
proper "value" for a field that is a relation to another model. This part adds the utility method on Model that should help in general.Also cleans up the slightly ugly mess from r8957. Backport of r9601 from trunk (the second piece of this patch is a bugfix, not just a tidy-up. It looks like it might be possible to have to_field setups that make the existing code fail and that's only hidden by the fact that inherited models with to_field relations to the parent fail for other reasons right now). git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@9603 bcc190cf-cafb-0310-a4f2-bffc1f526a37
-rw-r--r--django/db/models/base.py10
-rw-r--r--django/db/models/options.py1
-rw-r--r--django/forms/models.py8
3 files changed, 12 insertions, 7 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py
index bf6588d7fe..a561b80979 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -296,6 +296,16 @@ class Model(object):
pk = property(_get_pk_val, _set_pk_val)
+ def serializable_value(self, field_name):
+ """
+ Returns the value of the field name for this instance. If the field
+ is a foreign key, returns the id value, instead of the object.
+ Used to serialize a field's value (in the serializer, or form output,
+ for example).
+ """
+ field = self._meta.get_field_by_name(field_name)[0]
+ return getattr(self, field.attname)
+
def save(self, force_insert=False, force_update=False):
"""
Saves the current instance. Override this in a subclass if you want to
diff --git a/django/db/models/options.py b/django/db/models/options.py
index 6e0d6b5082..5d8a7b7104 100644
--- a/django/db/models/options.py
+++ b/django/db/models/options.py
@@ -448,3 +448,4 @@ class Options(object):
# objects.append(opts)
self._ordered_objects = objects
return self._ordered_objects
+
diff --git a/django/forms/models.py b/django/forms/models.py
index 65f20ad303..81a7439331 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -624,13 +624,7 @@ class ModelChoiceIterator(object):
def choice(self, obj):
if self.field.to_field_name:
- # FIXME: The try..except shouldn't be necessary here. But this is
- # going in just before 1.0, so I want to be careful. Will check it
- # out later.
- try:
- key = getattr(obj, self.field.to_field_name).pk
- except AttributeError:
- key = getattr(obj, self.field.to_field_name)
+ key = obj.serializable_value(self.field.to_field_name)
else:
key = obj.pk
return (key, self.field.label_from_instance(obj))