How to do automatic filtering based on the current user with tastypie

拜拜、爱过 提交于 2019-12-12 03:05:46

问题


I'm using tastypie with the DjangoAuthorization method.

I have a StudentResource like this :

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

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

So each of my student has many friends.

Now, I'd like to return, when my user is making an API call only his friends. (based on his django id). (I don't want to just add a filter to my Ressource, I really want the user to be only able to access to his friends)

I could override the GET method using the get_list tastypie function, but it seems pretty ugly.

So what is the good way to do that ?

Thx !


回答1:


I would use Nested Resources.

A GET call to /student/{{ id }}/friends would return the list of the student friends

You just have to override prepend_urls and define the method that will create the response




回答2:


If you do not want to use the "Per User Resource" documented here - http://django-tastypie.readthedocs.org/en/latest/cookbook.html#creating-per-user-resources,

my suggestion to you is to write an authorization middleware that filters the friends based on the user in question before the request continues to the tastypie resource. This way you would get only the student's friends in the resource.

refer to this link for creating a middleware - https://docs.djangoproject.com/en/dev/topics/http/middleware/

and pay close attention to the order of the middlwares.

You must place your middleware after the 'django.contrib.auth.middleware.AuthenticationMiddleware'




回答3:


Actually, the good way to do that is to create a custom Authorization for the StudentResource.

Here's the tastypie doc explaining that : http://django-tastypie.readthedocs.org/en/latest/authorization.html



来源:https://stackoverflow.com/questions/19707400/how-to-do-automatic-filtering-based-on-the-current-user-with-tastypie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!