Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@9601 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit d662ef554015a3508ff8100c73b370728156a02c 1 parent fa7aa72
@malcolmt malcolmt authored
View
10 django/db/models/base.py
@@ -296,6 +296,16 @@ def _set_pk_val(self, value):
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
View
1  django/db/models/options.py
@@ -448,3 +448,4 @@ def get_ordered_objects(self):
# objects.append(opts)
self._ordered_objects = objects
return self._ordered_objects
+
View
8 django/forms/models.py
@@ -624,13 +624,7 @@ def __iter__(self):
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))

0 comments on commit d662ef5

Please sign in to comment.
Something went wrong with that request. Please try again.