3

Tastypieを使用したDjangoで、オブジェクトの詳細のみを表示するようにリソースを構成する方法はありますか?

/user単一のユーザーオブジェクトを含むリストではなく、認証されたユーザーの詳細を返すURLが必要です。/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)
4

1 に答える 1

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クックブックで詳しく説明されています。

于 2012-12-09T07:51:51.783 に答える