Skip to content

Instantly share code, notes, and snippets.

@jmichalicek
Created October 26, 2012 19:34
Show Gist options
  • Select an option

  • Save jmichalicek/3960958 to your computer and use it in GitHub Desktop.

Select an option

Save jmichalicek/3960958 to your computer and use it in GitHub Desktop.
Togglable inline details for Tastypie resources
class InlineToggleMixIn(object):
"""
Allows details=<resource> querystring param to toggle whether to return resource uri or full details
"""
# based on handy dehydrate_related from
# http://chrismeyers.org/2012/06/25/tastypie-inline-aka-nested-fulltrue-embedded-relationship-dynamically-via-get-parameter/
# Be careful not to create an infinite loop from having multiple resources that reference each other using this
# and requesting details on both of them
def dehydrate_related(self, bundle, related_resource):
# this is not 100% ideal because the resource_name and collection_name may not be
# what the end user sees, depending on how things are named. They see the attribute name
resource_name = related_resource._meta.resource_name
collection_name = related_resource._meta.collection_name
inlines = bundle.request.GET.get('details','').split(',')
if resource_name in inlines or collection_name in inlines:
bundle = related_resource.build_bundle(obj=related_resource.instance, request=bundle.request)
return related_resource.full_dehydrate(bundle)
# default behavior for this method
return related_resource.get_resource_uri(bundle)
# Use these where you would have used a ToManyField or ToOneField
class ToManyFieldDetailToggle(InlineToggleMixIn, fields.ToManyField):
pass
class ToOneFieldDetailToggle(InlineToggleMixIn, fields.ToOneField):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment