如何利用tastypi对当前用户进行自动过滤

2024-09-30 20:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在djangauthorization方法中使用了tastype。在

我有这样一个学生资源:

class StudentResource(ModelResource):
  friends = fields.ToManyField(StudentResource, 'friends', null=True)

  class Meta:
    queryset = Student.objects.all()
    resource_name = 'student'
    authorization = DjangoAuthorization()

所以我的每个学生都有很多朋友。在

现在,我想返回,当我的用户只对他的朋友进行API调用时。(根据他的django身份证)。(我不想给我的资源添加一个过滤器,我真的希望用户只能访问他的朋友)

我可以使用GET_list tastype函数重写GET方法,但它看起来很难看。在

那么,怎样才能做到这一点呢?在

谢谢!在


Tags: 方法用户fieldsget朋友资源tastypenull
3条回答

我会用Nested Resources。在

/student/{{ id }}/friends的GET调用 会返回学生朋友的名单

您只需重写prepend_urls并定义将创建响应的方法

实际上,最好的方法是为StudentResource创建一个自定义授权。在

以下是Tastype医生的解释:http://django-tastypie.readthedocs.org/en/latest/authorization.html

如果您不想使用这里记录的“每用户资源”-http://django-tastypie.readthedocs.org/en/latest/cookbook.html#creating-per-user-resources

我给您的建议是编写一个授权中间件,在请求继续发送到tastype资源之前,它将根据所讨论的用户过滤朋友。 这样你就只能在资源中找到学生的朋友。在

请参阅此链接以创建中间件-https://docs.djangoproject.com/en/dev/topics/http/middleware/

密切注意中餐的秩序。在

必须将中间件放在'django.contrib.auth公司.中间件.认证中间件'

相关问题 更多 >