sur*_*kal 3 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)
Run Code Online (Sandbox Code Playgroud)
我能够通过使用以下资源方法的组合来完成此操作
示例用户资源
#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"),
]
Run Code Online (Sandbox Code Playgroud)
在Tastypie Cookbook中更详细地解释了使用除主键之外的其他内容来获取资源的详细信息
| 归档时间: |
|
| 查看次数: |
2064 次 |
| 最近记录: |