Created
April 18, 2014 20:11
-
-
Save marshallds/11062289 to your computer and use it in GitHub Desktop.
TastyPie nested resourceful routes mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.