Skip to content

Instantly share code, notes, and snippets.

@beardedeagle
Created April 26, 2015 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beardedeagle/5a15677f25ba153d4ef3 to your computer and use it in GitHub Desktop.
Save beardedeagle/5a15677f25ba153d4ef3 to your computer and use it in GitHub Desktop.
full_dehydrate mixin to allow for field selection in Tastypie
class fieldSelectMixin(object):
"""
Mixin to allow field selection. full_dehydrate method.
"""
def full_dehydrate(self, bundle, for_list=False):
"""
Given a bundle with an object instance, extract the information from it
to populate the resource.
"""
use_in = ['all', 'list' if for_list else 'detail']
# Get values if fields is set in query
selectedFields = bundle.request.GET.get('fields')
# If selectedFields has data turn it into a list
if selectedFields:
selectedFields = selectedFields.split(',')
# Dehydrate each field.
for field_name, field_object in self.fields.items():
# If it's not for use in this mode, skip
field_use_in = getattr(field_object, 'use_in', 'all')
if callable(field_use_in):
if not field_use_in(bundle):
continue
else:
if field_use_in not in use_in:
continue
# If fields is set in query paramaters filter field_name
# and discard any not in selectedFields
if selectedFields:
if field_name not in selectedFields:
continue
# 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, for_list=for_list)
# 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)
bundle = self.dehydrate(bundle)
return bundle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment