[Django]-Django Tastypie โ€“ Resource with object details only

6๐Ÿ‘

โœ…

I was able to do this by using a combination of the following resource methods

Example user resource

#Django
from django.contrib.auth.models import User
from django.conf.urls import url

#Tasty
from tastypie.resources import ModelResource

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'

        #Disallow list operations
        list_allowed_methods = []
        detail_allowed_methods = ['get', 'put', 'patch']

        #Exclude some fields
        excludes = ('first_name', 'is_active', 'is_staff', 'is_superuser', 'last_name', 'password',)

    #Apply filter for the requesting user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    #Override urls such that GET:users/ is actually the user detail endpoint
    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]

Using something other than the primary key for getting the details of a resource is explained in more detail in the Tastypie Cookbook

๐Ÿ‘คjpennell

Leave a comment