Created
October 26, 2012 19:34
-
-
Save jmichalicek/3960958 to your computer and use it in GitHub Desktop.
Togglable inline details for Tastypie resources
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
| 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