2012-11-23 32 views
3

在Django中,使用Tastypie,是否有配置资源的方法,使其仅显示对象详细信息?Django Tastypie - 仅包含对象细节的资源

我想要一个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) 
+0

解释你有什么这么远吗?播下你的代码 - 它看起来像你正在使用[obj_get_list](http://django-tastypie.readthedocs.org/en/latest/resources.html#id9)而不是[obj_get](http:// django-tastypie .readthedocs.org/EN /最新/ resources.html#ID10)。 – Tadeck

+0

@Tadeck我将我的代码的相关部分添加到问题中。我没有明确使用任何这些方法,但我想我总是使用'obj_get'。 – surjikal

回答

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

+6

请注意'apply_authorization_limits'已被弃用。 [见](https://github.com/toastdriven/django-tastypie/issues/809) – w43L

+0

那么我们如何才能在更高版本中实现相同的结果? – Gabriel

相关问题