Created
July 24, 2014 10:56
-
-
Save bogsio/9c0a95ac7e0252f0dccf to your computer and use it in GitHub Desktop.
TPT3 - Adding custom resource method
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 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