Django 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)

我能够使用以下资源方法的组合来做到这一点

  • override_urls
  • apply_authorization_limits

示例用户资源

#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 食谱中有更详细的说明

相关内容

最新更新