Last active
June 7, 2017 15:36
-
-
Save miraculixx/eb4c234857b662a458d0 to your computer and use it in GitHub Desktop.
select tastypie fields returned by the api
This file contains 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 FieldSelectionMixin(object): | |
""" | |
add ability to Resource to query specific fields. This works by | |
removing any fields not in the fields list provided by the fields | |
query parameter. | |
Programming Use: | |
class MyResource(FieldSelectionMixin, ModelResource): | |
... | |
(as with any normal resource) | |
API Use: | |
/my/api/myresource/?fields=field[,field[, ...]] | |
/my/api/myresource/<pk>?fields=field[,field[, ...]] | |
For debugging purpose, add &fields_debug=1 to retrieve the list | |
of fields removed and those actually selected: | |
{ | |
'_fields_removed' : [ 'field1', 'field2', ... ], | |
'_fields_selected' : [ 'field1', 'field2', ... ], | |
<actual data> | |
} | |
""" | |
def dehydrate(self, bundle): | |
""" | |
remove fields not requested | |
note: this is called for every object, so works for both detail and | |
list requests | |
""" | |
only_fields = bundle.request.GET.get('fields') | |
debug_fields = bundle.request.GET.get('fields_debug', False) | |
if only_fields: | |
only_fields = only_fields.split(',') | |
fields_to_remove = [field for field in bundle.data.keys() | |
if field not in only_fields] | |
for field in fields_to_remove: | |
del bundle.data[field] | |
if debug_fields: | |
bundle.data['_fields_selected'] = [field for field in only_fields | |
if field in bundle.data.keys()] | |
bundle.data['_fields_removed'] = fields_to_remove | |
return bundle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment