Nested resources in Tastypie

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)



Ukraine x 1, Spain x 1, Netherlands x 5, Germany x 2, Slovakia x 1, United States x 8, India x 1, Norway x 1, Romania x 1, Sweden x 1, China x 1

If you found this post useful, funny or whatever, let us know without writing a full comment!

comments powered by Disqus

Search Bar

Categories

Latest Tweets