如何使用tastypie基于当前用户进行自动过滤

时间:2013-10-31 13:08:58

标签: python django filtering tastypie

我正在使用带有DjangoAuthorization方法的tastypie。

我有这样的StudentResource:

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

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

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

现在,我想回复,当我的用户只为他的朋友打API时。 (基于他的django id)。 (我不想只为我的Ressource添加一个过滤器,我真的希望用户只能访问他的朋友)

我可以使用get_list tastypie函数覆盖GET方法,但它看起来很难看。

那么这样做的好方法是什么?

Thx!

3 个答案:

答案 0 :(得分:0)

我会使用Nested Resources

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

您只需覆盖prepend_urls并定义将创建响应的方法

答案 1 :(得分:0)

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

我的建议是编写一个授权中间件,在请求继续到tastypie资源之前根据有问题的用户过滤朋友。 通过这种方式,您只能获得资源中学生的朋友。

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

并密切关注middlware的顺序。

您必须将中间件放在'django.contrib.auth.middleware.AuthenticationMiddleware'之后

答案 2 :(得分:0)

实际上,这样做的好方法是为StudentResource创建自定义授权。

以下是tastypie文档解释:http://django-tastypie.readthedocs.org/en/latest/authorization.html