Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.0.X] The first step in fixing a group of problems related to outpu…

…tting 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
  • Loading branch information...
commit bffb45786297b11e6f189c302d084afca670709a 1 parent 85e1d87
Malcolm Tredinnick authored December 08, 2008
10  django/db/models/base.py
@@ -296,6 +296,16 @@ def _set_pk_val(self, value):
296 296
 
297 297
     pk = property(_get_pk_val, _set_pk_val)
298 298
 
  299
+    def serializable_value(self, field_name):
  300
+        """
  301
+        Returns the value of the field name for this instance. If the field
  302
+        is a foreign key, returns the id value, instead of the object.
  303
+        Used to serialize a field's value (in the serializer, or form output,
  304
+        for example).
  305
+        """
  306
+        field = self._meta.get_field_by_name(field_name)[0]
  307
+        return getattr(self, field.attname)
  308
+
299 309
     def save(self, force_insert=False, force_update=False):
300 310
         """
301 311
         Saves the current instance. Override this in a subclass if you want to
1  django/db/models/options.py
@@ -448,3 +448,4 @@ def get_ordered_objects(self):
448 448
             #        objects.append(opts)
449 449
             self._ordered_objects = objects
450 450
         return self._ordered_objects
  451
+
8  django/forms/models.py
@@ -624,13 +624,7 @@ def __iter__(self):
624 624
 
625 625
     def choice(self, obj):
626 626
         if self.field.to_field_name:
627  
-            # FIXME: The try..except shouldn't be necessary here. But this is
628  
-            # going in just before 1.0, so I want to be careful. Will check it
629  
-            # out later.
630  
-            try:
631  
-                key = getattr(obj, self.field.to_field_name).pk
632  
-            except AttributeError:
633  
-                key = getattr(obj, self.field.to_field_name)
  627
+            key = obj.serializable_value(self.field.to_field_name)
634 628
         else:
635 629
             key = obj.pk
636 630
         return (key, self.field.label_from_instance(obj))

0 notes on commit bffb457

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