【问题标题】:How to do automatic filtering based on the current user with tastypie如何使用tastepie根据当前用户进行自动过滤
【发布时间】:2013-11-11 12:15:48
【问题描述】:

我在 DjangoAuthorization 方法中使用 sweetpie。

我有一个这样的 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)。 (我不想只是在我的资源中添加过滤器,我真的希望用户只能访问他的朋友)

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

那么有什么好的方法呢?

谢谢!

【问题讨论】:

    标签: python django filtering tastypie


    【解决方案1】:

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

    这里有一份美味的文档解释:http://django-tastypie.readthedocs.org/en/latest/authorization.html

    【讨论】:

      【解决方案2】:

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

      我给你的建议是编写一个授权中间件,在请求继续到美味派资源之前根据相关用户过滤朋友。 这样您就只能在资源中找到学生的朋友。

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

      并密切关注中间件的顺序。

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

      【讨论】:

      • 非常感谢,我实际上正在寻找“每用户资源”文档(我不知道它存在)!
      【解决方案3】:

      我会使用Nested Resources

      /student/{{ id }}/friends 的 GET 调用 将返回学生朋友的列表

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

      【讨论】:

      • 确实可以,但我真的希望我的网址 /student/?format=json 只返回用户的朋友。
      • 通过添加你的学生证参数?
      • 什么意思?我不能只调用 url /student/{{ id }}/,它会返回关于我学生的信息,而不是他的朋友。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多