Skip to content

Instantly share code, notes, and snippets.

@bogsio
Created July 24, 2014 10:56
Show Gist options
  • Save bogsio/9c0a95ac7e0252f0dccf to your computer and use it in GitHub Desktop.
Save bogsio/9c0a95ac7e0252f0dccf to your computer and use it in GitHub Desktop.
TPT3 - Adding custom resource method
class TodoListResource(ModelResource):
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/stats%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('stats'), name="api_list_stats"),
]
def dehydrate(self, bundle):
items = bundle.obj.items.all()
bundle.data['item_count'] = items.count()
bundle.data['items'] = [i.to_dict() for i in items]
return bundle
def stats(self, request, **kwargs):
stats = {}
stats['list_count'] = request.user.todo_lists.all().count()
stats['item_count'] = TodoItem.objects.filter(
todo_list_id__in=[l.id for l in request.user.todo_lists.all()]).count()
return self.create_response(request, stats)
class Meta:
authentication = SessionAuthentication()
authorization = AuthorizationByUser()
queryset = TodoList.objects.all()
resource_name = 'list'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment