Search code examples
pythondjangotastypie

How does tastypie handle comlex url?


Tastypie can automatically generate urlpattern for simple resource urls.

For example, /user/1/ , /group/2/, I only need to define UserResource and GroupResource

But what if I have API url like /group/2/user/, saying I want to retrieve all users in group 2.

Does tastypie have any solution to handle this?


Solution

  • You can use the tastypie.Resource.prepend_urls method:

    from django.conf.urls import url
    from tastypie.utils import trailing_slash
    
    class MyResource(Resource):
        def prepend_urls(self):
            return [
                url(r"^(?P<resource_name>%s)/(?P<%s>.*?)/user%s$" % (self._meta.resource_name, self._meta.detail_uri_name, trailing_slash()), self.wrap_view('group_user'), name="api_group_user"),
            ]
    
        def group_user(self, request, **kwargs):
            # Your API view.
            return self.create_response(request, {})
    

    I usually create a shortcut method that those long, ugly urls:

    def create_detail_url(url_string, view_method_name, view_name):
        url_string = r"^(?P<resource_name>%s)/(?P<%s>.*?)" + url_string + r"%s$"
        url_string = url_string % (self._meta.resource_name, self._meta.detail_uri_name, trailing_slash())
        return url(url_string, self.wrap_view(view_method_name), name="api_" + view_name)
    

    Which makes the prepend_urls method look like this:

    def prepend_urls(self):
        return [
            create_detail_url(r"/user", "group_user", "group_user"),
        ]