我正在使用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