Search code examples
pythondjangotastypie

Django - Tastypie provide summary of data returned


Hi I have a resource named employees which have 10 columns. How can I create a /employees/summary/ endpoint which only returns 5 columns but have all features of the main /employees/ endpoint such as filters and ordering. What i have tried to do is modify the result from get_list() but thats turning out to be hard.

class EmployeeResouece(ModelResource):
    class Meta:
        queryset = Employees.objects.all()
        resource_name = 'employees'
        allowed_methods = ['get','post','put','patch']
    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/summary%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('summary'), name="summary"),
        ]
    def summary(self, request, **kwargs):
        result=EmployeeResouece().get_list(request)
### LIMIT COLUMNS TO 5###
        return result

Solution

  • Found a solution by pasting the code for get_list method in resources.py

    base_bundle = self.build_bundle(request=request)
            objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs))
            sorted_objects = self.apply_sorting(objects, options=request.GET)
    
        paginator = self._meta.paginator_class(request.GET, sorted_objects, resource_uri=self.get_resource_uri(), limit=self._meta.limit, max_limit=self._meta.max_limit, collection_name=self._meta.collection_name)
        to_be_serialized = paginator.page()
    
        # Dehydrate the bundles in preparation for serialization.
        bundles = [
            self.full_dehydrate(self.build_bundle(obj=obj, request=request), for_list=True)
            for obj in to_be_serialized[self._meta.collection_name]
        ]
    
        whitelist_columns=['id','name','dept']
        for bundle in bundles:
            bundle.data = { k : v for k,v in bundle.data.items() if k in whitelist_columns}
    
        to_be_serialized[self._meta.collection_name] = bundles
        to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)
        return self.create_response(request, to_be_serialized)
    

    Not the best method, as I am not using the in build excludes or fields meta data. But it works. If detail level implementation is needed, add a prepend_url and change the code in get_detail, your url regex needs to handle primary keys