限制仅访问拥有的内容 django

Pry*_*die 5 python django tastypie django-guardian

我正在使用django-tastypie编写 API 。我有两个自定义权限问题,希望django-guardian能够解决。

我有两个用户组临床医生和患者。临床医生应该能够访问仅属于其患者的对象,并且患者应该只能访问他们自己创建的对象。

我的代码如下:

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,
        }
Run Code Online (Sandbox Code Playgroud)

我如何使用权限来限制对此的访问BlogPostResource

Pry*_*die 3

我的最终解决方案基于@JamesO答案。他的答案的问题是它是在 类被重写之前为旧版本的 django-tastypie 编写的。这是我的代码以供将来参考:Authorization

from tastypie.authorization import Authorization
from django.contrib.auth.models import Group
from extendedusers.models import ExtendedUser


class CustomAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        clinician_group = Group.objects.get(name='clinician')
        if bundle.request and hasattr(bundle.request, 'user'):
            if clinician_group in bundle.request.user.groups.all():
                patients = ExtendedUser.objects.filter(clinician_id=bundle.request.user.id)
                object_list = object_list.filter(author__id__in=patients)
            else:
                object_list = object_list.filter(author=bundle.request.user)
            return object_list
        else:
            return object_list.none()
Run Code Online (Sandbox Code Playgroud)