Serializing Foreign Key in Django Model
Django comes with a powerful serialization mechanism to convert your models to XML, JSON, YAML, and even python objects. However, the default serializer won't serialize the entire fields of another model if a foreign key field is pointing to it.
Django 1.2 introduced natural keys to address this issue, but if you cannot change your foreign key class like the default User authentication class, you won't have any option but do create a subclass of Serializer module and override handle_fk_field method in it.
The following is an example of overriding handle_fk_field method for serializing the username field instead of user_field field.
# Serializing ForeignKey in Django
class SerializersUser(Serializer):
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).
"""
self._start_relational_field(field)
related = getattr(obj, field.name)
if related is not None:
if self.use_natural_keys and hasattr(related, 'natural_key'):
# If related object has a natural key, use it
related = related.natural_key()
# Iterable natural keys are rolled out as subelements
for key_value in related:
self.xml.startElement("natural", {})
self.xml.characters(smart_unicode(key_value))
self.xml.endElement("natural")
else:
if field.rel.field_name == related._meta.pk.name:
# Obtain username field instead of the PK field.
related = getattr(related, "username")
else:
# Related to remote object via other field
related = getattr(related, field.rel.field_name)
self.xml.characters(smart_unicode(related))
else:
self.xml.addQuickElement("None")
self.xml.endElement("field")
Published On: Aug. 1, 2010 --- Views: 1614
Tags:
There are 0 comment(s):