Django Tastypie - 仅限对象详细信息的资源

时间:2012-11-23 00:58:11

标签: python django rest tastypie

在使用Tastypie的Django中,有没有办法配置资源,只显示对象详细信息?

我想要一个url /user,它返回经过身份验证的用户的详细信息,而不是包含单个用户对象的列表。我不想使用/users/<id>来获取用户的详细信息。

这是我的代码的相关部分:

from django.contrib.auth.models import User
from tastypie.resources import ModelResource

class UserResource(ModelResource):

    class Meta:
        queryset        = User.objects.all()
        resource_name   = 'user'
        allowed_methods = ['get', 'put']
        serializer      = SERIALIZER      # Assume those are defined...
        authentication  = AUTHENTICATION  # "
        authorization   = AUTHORIZATION   # "

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

1 个答案:

答案 0 :(得分:6)

我能够通过使用以下资源方法的组合来实现这一目标

示例用户资源

#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"),
        ]

Tastypie Cookbook

更详细地介绍了使用主键之外的其他内容来获取资源的详细信息。