Skip to content

Instantly share code, notes, and snippets.

@bohde
Created February 10, 2012 03:17
Show Gist options
  • Select an option

  • Save bohde/1786061 to your computer and use it in GitHub Desktop.

Select an option

Save bohde/1786061 to your computer and use it in GitHub Desktop.
from django.db.models.sql.constants import LOOKUP_SEP
from tastypie.fields import ToOneField
class NestedToOneField(ToOneField):
def dehydrate(self, bundle):
try:
foreign_obj = reduce(lambda obj, attr: getattr(obj, attr), self.attribute.split(LOOKUP_SEP), bundle.obj)
except ObjectDoesNotExist:
foreign_obj = None
if not foreign_obj:
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))
return None
self.fk_resource = self.get_related_resource(foreign_obj)
fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
return self.dehydrate_related(fk_bundle, self.fk_resource)
class EntryResource(ModelResource):
subject = NestedToOneField(SubjectResource,'page__topic__chapter__subject',full=True)
# Rest like normal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment