achilles
achilles

Reputation: 325

django - how to return two serializer in a response

I have two variable that i want to return: - serializer1.data and serializer2.data. I don't know how return 2 variable like : return Response(serializer1.data (and) serializer2.data, status=...). Any help is appreciated.

Upvotes: 3

Views: 2105

Answers (2)

Michael Camilo
Michael Camilo

Reputation: 71

If you are only returning something like

return Response(serializer1.data)

And you want to add a second serializer data, the best way to don't change your response it to return:

return Response(serializer1.data + serializer2.data)

As ReturnList the first serializer data will be extended with the second. That way you will not have to iterate on endpoint's response.

Upvotes: 0

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

You can use the list comprehension of Python.

Like this:

    Serializer_list = [serializer1.data, serializer2.data]

    content = {
        'status': 1, 
        'responseCode' : status.HTTP_200_OK, 
        'data': Serializer_list,

        }
    return Response(content)

And then use a for loop on data[0] variable.

Upvotes: 2

Related Questions