我已经知道如何在tastypie中创建ModelResource。例如,我在 resources.py 中有用户资源,在 models.py 中有用户资源。但是,在 views.py 中,我有一个名为match_user的视图,它获取所有用户的列表并与request.user匹配。它返回一个名为mymatch.html的render_to_response html。一切都可以在浏览器上运行,但我想为这个特定match_user创建一个 API。我该怎么做?
谢谢
我认为以下内容回答了您的问题:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = "user"
authentication = SessionAuthentication()
# User is only authorized to view his own details
def apply_authorization_limits(self, request, object_list):
return object_list.filter(pk=request.user.pk)
如果用户具有活动会话并且已登录,则会话身份验证将起作用。有关更多身份验证选项,请参阅 https://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html?highlight=authentication#authentication-options