Skip to content

Instantly share code, notes, and snippets.

@dericcrago
Created February 11, 2012 13:13
Show Gist options
  • Save dericcrago/1799364 to your computer and use it in GitHub Desktop.
Save dericcrago/1799364 to your computer and use it in GitHub Desktop.
display the projects field if it was a ``detail`` response
from tastypie import fields
from tastypie.resources import ModelResource
from company.models import Company
class CompanyResource(ModelResource):
"""
Tastypie resource for Company
"""
class Meta:
queryset = Company.objects.all()
resource_name = 'companies'
additional_detail_fields = {'projects': fields.ToManyField('api.resources.ProjectResource', 'projects',full=True)}
def dehydrate(self, bundle):
# detect if detail
if self.get_resource_uri(bundle) == bundle.request.path:
# detail detected, include additional fields
bundle = self.extra_dehydrate(bundle, self._meta.additional_detail_fields)
return bundle
# extra_dehydrate is basically full_dehydrate
# except we'll loop over the additional_detail_fields
# and we won't want to do the dehydrate(bundle) at the end
def extra_dehydrate(self, bundle, fields=None):
"""
Given a bundle with an object instance, extract the information from it
to populate the resource.
"""
# Dehydrate each field.
# loop over additional_detail_fields instead
#for field_name, field_object in self.fields.items():
for field_name, field_object in fields.items():
# A touch leaky but it makes URI resolution work.
if getattr(field_object, 'dehydrated_type', None) == 'related':
field_object.api_name = self._meta.api_name
field_object.resource_name = self._meta.resource_name
bundle.data[field_name] = field_object.dehydrate(bundle)
# Check for an optional method to do further dehydration.
method = getattr(self, "dehydrate_%s" % field_name, None)
if method:
bundle.data[field_name] = method(bundle)
# dehydrating the bundle will create an infinite loop
#bundle = self.dehydrate(bundle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment