manabreak
manabreak

Reputation: 5597

How to combine two similar views into a single response?

I have two similar views that return the same serialized responses. The views are like this:

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)

And the serializers are like this:

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')

And finally, the models look like this:

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')

Since these two views and serializers return essentially the same data (an ID field, a name field and user profile info) and use the same request parameters (the current user), I'd like to combine these two into one. How do I do that? In the end, I'd like the serialized response to contain the results of both query sets.

Upvotes: 3

Views: 2041

Answers (1)

dukebody
dukebody

Reputation: 7185

Since serializer.data will be a list of dictionaries in your case, I'd try concatenating the results of both serializers for the response:

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)

Does this make sense? :)

Upvotes: 6

Related Questions