如何将两个相似的视图合并为一个响应?

时间:2015-09-08 09:43:12

标签: python django serialization django-rest-framework

我有两个相似的视图返回相同的序列化响应。意见是这样的:

class GetFoos(generics.ListAPIView):
    # init stuff here

    def list(self, request):
        queryset = Foo.objects.filter(owner = request.user)
        serializer = FooSerializer(queryset, many = True)
        return Response(serializer.data, status = status.HTTP_200_OK)

class GetFooResponses(generics.ListAPIView):
    # init stuff here

    def list(self, request):
        queryset = FooResponse.objects.filter(owner = request.user)
        serializer = FooResponseSerializer(queryset, many = True)
        return Response(serializer.data, status = status.HTTP_200_OK)

序列化器是这样的:

class FooSerializer(serializers.ModelSerializer):
    user = serializers.ProfileInfoSerializer(source = 'owner.userprofile', read_only = True)

    class Meta:
        model = Foo
        fields = ('id', 'name', 'user')

class FooResponseSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source = 'foo.id')
    name = serializers.ReadOnlyField(source = 'foo.name')
    user = serializers.ProfileInfoSerializer(source = 'owner.userprofile', read_only = True)

    class Meta:
        model = FooResponse
        fields = ('id', 'name', 'user')

最后,模型看起来像这样:

class Foo(models.Model):
    owner = ForeignKey('auth.User', related_name = 'foos')
    name = models.CharField()

class FooResponse(models.Model):
    owner = ForeignKey('auth.User', related_name = 'responses')
    foo = ForeignKey(Foo, related_name = 'responses')

由于这两个视图和序列化器基本上返回相同的数据(ID字段,名称字段和用户配置文件信息)并使用相同的请求参数(当前用户),因此我想将这两者合并为一个。我怎么做?最后,我希望序列化响应包含两个查询集的结果。

1 个答案:

答案 0 :(得分:1)

由于serializer.data将是您的案例中的字典列表,我会尝试连接响应的两个序列化器的结果:

class GetFoosAndResponses(generics.ListAPIView):
    # init stuff here

    def list(self, request):
        foo_queryset = Foo.objects.filter(owner=request.user)
        foo_serializer = FooSerializer(foo_queryset, many=True)

        foo_response_queryset = FooResponse.objects.filter(owner=request.user)
        foo_response_serializer = FooResponseSerializer(foo_response_queryset, many=True)

        return Response(foo_serializer.data + foo_response_serializer.data, status=status.HTTP_200_OK)

这有意义吗? :)