Nested resources in Tastypie

2 oktober 2012 - Joeri - django - tastypie - Software

The way Django Tastypie explains nested resources in their documentation is somewhat ackward and comes with several drawbacks:

  • Authentication simply does not work.
  • You are repeating yourself with object not found and multiple objects found checks.

The alternative approach they describe suddenly asks you to change your main urls.py. Weird.

Instead of doing what is described in the Tastypie cookbook regarding nested resources, you can achieve the same thing with more elegant code:

class ParentResource(ModelResource):
    def override_urls(self): # prepend_urls in 0.9.12
        return [
            url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/child%s$' % (
                self._meta.resource_name, trailing_slash()),
                self.wrap_view('dispatch_child'),
                name='api_parent_child'),
        ]

    def dispatch_child(self, request, **kwargs):
        return ChildResource().dispatch('list', request, **kwargs)



Latest Tweets