Search code examples
djangotastypie

Tastypie Django, Custom view with prepend_url


I am trying to make a custom endpoint for my REST interface, but have some problems.. hope someone can help me out ;)

I want to make a custom view of a resource, but I still want the default pagination features.

class ShareResource(ModelResource):
    .....

    def prepend_urls(self):
            return [
                url(r"^(?P<resource_name>%s)/dialog/(?P<account_id>\w[\w/-]*)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dialog'), name="api_dialog"),
            ]

    def dialog(self, request, **kwargs):
            self.method_check(request, allowed=['get'])
            self.is_authenticated(request)

            account_id = kwargs['account_id']

            shares = Share.objects.filter(
                Q(account=request.user.account, post__account__id=account_id) |
                Q(post__account=request.user.account, account=account_id)
            ).order_by("-created")

            raise Exception(shares)

            return self.get_list(request, objects=shares)

my problem is with the function "get_list" .. is there an alternativ that take objects a arg? or is there a better way to make a custom view?


Solution

  • Try overriding obj_get_list instead: https://github.com/django-tastypie/django-tastypie/blob/master/tastypie/resources.py#L2124

    You'll want to pop account_id off kwargs and filter by that.

    Also, don't just filter the result of the default obj_get_list method, you'll need authorized_read_list to be called after any filtering is performed for security reasons.