Django REST框架:使用来自两个不同URL的相同查询集

时间:2014-06-19 08:09:09

标签: django django-rest-framework

我有GroupsMemberships的两个ModelViewSets:

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsGroupOwnerOrSuperuser,)
    ...


class MembershipViewSet(viewsets.ModelViewSet):
    queryset = Membership.objects.all()
    serializer_class = MembershipSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsMemberOrSuperuser,)

    def get_queryset(self):
        ...
        # do some stuff including filter query by group
        group_id = self.request.QUERY_PARAMS.get('group_id', None)
        ...
        return queryset

MembershipViewSet中,get_queryset允许您的查询按group_id进行过滤,以获取与特定群组相关联的成员。

GroupViewSet中,我还希望允许按网址/groups/{pk}/memberships按群组进行过滤:

    @link()
    def memberships(self, request, pk=None):
        ...

但我不想通过从get_queryset复制MembershipsViewSet代码来破坏DRY。所以类似下面的代码,虽然它不起作用:

@link()
def memberships(self, request, pk=None):
    group = Group.objects.get(pk=pk)
    # The following doesn't work because QUERY_PARAMS is immutable
    self.request.QUERY_PARAMS.update({'group_id':pk})
    mems = MembershipViewSet.get_queryset(self)
    mems = MembershipSerializer(mems, many=true, context={'request': request})
    return Response(mems.data)

所以问题是:如何重定向或至少重新使用代码,以便从两个不同的DRF URL返回相同的结果?

1 个答案:

答案 0 :(得分:0)

我不知道这是否能解决您的问题,但您可以替换此行

# The following doesn't work because QUERY_PARAMS is immutable
self.request.QUERY_PARAMS.update({'group_id':pk})

self.kwargs['group_id'] = pk

然后在 get_queryset 中,您可以采用相同的方式获取组ID。

group_id = self.kwargs.get('group_id', None)

这就是我通常的做法,它对我有用。希望这会有所帮助。