Created
February 10, 2012 03:17
-
-
Save bohde/1786061 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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