我正在使用django-tastypie編寫API。我有兩個定製permisions問題,我希望django-guardian可以修復。限制對僅擁有內容的訪問django
我有兩個用戶組臨牀醫師和患者。臨牀醫生應該能夠訪問屬於他們患者的對象,並且患者應該只能夠訪問由他們自己創建的對象。
我的代碼如下:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
class BlogPostResource(ModelResource):
author = fields.ToOneField(UserResource, 'author', full=True)
class Meta:
queryset = BlogPost.objects.all()
resource_name = 'posts'
allowed_methods = ["get", "post"]
# Add it here.
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
filtering = {
'author': ALL_WITH_RELATIONS,
}
我怎樣才能使用權限來限制對這個BlogPostResource
訪問?
class CustomAuthorization(Authorization):
def apply_limits(self, request, object_list):
...
clin_group = Group.objects.get(name='YOUR GROUP')
if request and hasattr(request, 'user'):
if clin_group in request.user.groups.all():
object_list = object_list.filter(user__in=request.user.patients.all()) # or however you stop clinician>patient relation
else:
object_list = object_list.filter(user=request.user)
return object_list
長期可擴展性,請參閱http://stackoverflow.com/a/16261711/454615 – airtonix 2013-04-28 10:04:08