6

我对 Django & Tastypie 很陌生。我想只返回查询中的一个对象。我几乎尝试了所有方法,但似乎找不到解决方案。下面是我的代码:

class ProfileResource(ModelResource):
     person = fields.ForeignKey(UserResource, 'user', full=True)

class Meta:
    queryset = Person.objects.all()
    resource_name = 'profile'
    authentication = BasicAuthentication()
    authorization = DjangoAuthorization()
    serializer = Serializer(formats=['json'])

现在我遇到问题的部分是如何使用request.user.

4

1 回答 1

4

如果您只想显示一个资源,我可能会创建新的资源视图(命名为 my_profile),它会在 kwargs 中使用用户调用普通详细视图并删除其他 url:

from django.conf.urls import url
from tastypie.utils import trailing_slash
class ProfileResource(ModelResource):
    ...
    def base_urls(self):
        return [
            url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_my_profile'), name="api_dispatch_my_profile")
        ]

    def dispatch_my_profile(self, request, **kwargs):
        kwargs['user'] = request.user
        return super(ProfileResource, self).dispatch_detail(request, **kwargs)
于 2012-10-24T12:16:12.447 回答