问题
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