Skip to content

Instantly share code, notes, and snippets.

@marshallds
Created April 18, 2014 20:11
Show Gist options
  • Save marshallds/11062289 to your computer and use it in GitHub Desktop.
Save marshallds/11062289 to your computer and use it in GitHub Desktop.
TastyPie nested resourceful routes mixin
from django.conf.urls import url
from tastypie.http import HttpGone, HttpMultipleChoices
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from tastypie.resources import ModelResource
from recipes.models import Recipe, Ingredient
class NestedResourceMixin(object):
def prepend_urls(self):
resources = super(NestedResourceMixin, self).prepend_urls()
resources += [
url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/%s/' % (self._meta.resource_name, resource._meta.resource_name),
self.wrap_view('get_nested_resource'), {'resource':resource})
for resource in self._meta.nested_resources
]
return resources
def get_nested_resource(self, request, **kwargs):
nested_resource = kwargs['resource']()
del kwargs['resource']
try:
obj = self.cached_obj_get(self.build_bundle(request=request), **self.remove_api_resource_names(kwargs))
except ObjectDoesNotExist:
return HttpGone()
except MultipleObjectsReturned:
return HttpMultipleChoices("there were MultipleObjectsReturned")
this_resources_name = self._meta.object_class._meta.object_name.lower()
return nested_resource.get_detail(request, **{'%s__pk' % this_resources_name: obj.pk})
class IngredientResource(ModelResource):
class Meta:
queryset = Ingredient.objects.all()
resource_name = 'ingredients'
class RecipeResource(NestedResourceMixin, ModelResource):
class Meta:
queryset = Recipe.objects.all()
resource_name = 'recipes'
nested_resources = [IngredientResource]
@marshallds
Copy link
Author

This is a first stab at a mixin to provide nested routes with tastypie. There are a couple of potential gotchas with this version. It makes the assumption that the nested resource's model has a field with the same name as the parent resource's model (lowercased) and that it is referenced by pk. It also requires nested resources to come before the parent resource in the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment