DRF - 限制对象返回给所有者

时间:2016-01-03 19:12:26

标签: django django-rest-framework

我有一个模特

class Widget(models.Model):
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=1024)
    username = models.CharField(max_length=50)
    code = models.CharField(max_length=1024)
    owner = models.ForeignKey('MyappUser', related_name='Myapp_owner')
    list = models.ForeignKey('WidgetList')

我希望能够做的是在调用特定视图时 -

class WidgetList(generics.ListCreateAPIView):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer
    filter_class = WidgetFilter

我只想要用户拥有的小部件登录。

我目前的过滤器是 -

class WidgetFilter(django_filters.FilterSet):
    owner = django_filters.NumberFilter(name="owner", lookup_type="exact")
    list = django_filters.NumberFilter(name="list", lookup_type="exact")

    class Meta:
        model = Widget
        fields = ['owner', 'list']

现在我必须做/api/widgets/?owner=3&list=5

但这并不妨碍其他用户查看小部件。

我以前使用以下方法进行此操作,但它破坏了我进行过滤器类的能力 -

class WidgetList(generics.ListCreateAPIView):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer


    def get(self, request):
        if request.user:
            queryset = self.get_queryset().filter(owner=request.user)
            for object in queryset:
                object.code = decrypt_code(masterkey,
                                                   personalkey,
                                                   object.code)
        else:
            queryset = self.get_queryset()

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = WidgetSerializer(queryset, many=True)
        return Response(serializer.data)

我想要做的是,如果我有这样的列表 -

Jane
Widget 1
Widget List ABC

Jane
Widget 2
Widget List DEF (which is 3)

Mike (which is 3)
Widget 3
Widget List ABC (which is 5)

Alfred
Widget 4
Widget List ABC

如果我以/api/widgets/?list=5身份登录,如果我以迈克身份登录,我只想查看Widget 3

1 个答案:

答案 0 :(得分:1)

来自文档:

  

请注意,您可以同时使用被覆盖的.get_queryset()和通用   一起过滤,一切都会按预期工作。

所以我会这样做:

class WidgetList(generics.ListCreateAPIView):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer
    filter_class = WidgetFilter


    def get_queryset(self):
        owner = self.request.user
        return super(WidgetList, self).get_queryset().filter(owner=request.user)

我没有设法测试代码,但我的期望是get_queryset只会返回由所有者过滤的条目。因此它不会包含其他用户的条目。