0

I know, I can return a single object through Django viewsets for any method. But can I return multiple objects through the API? I have something like this:

class SomeViewSet(viewsets.ModelViewset):
    queryset = SomeModel.objects.all()
    serializer_class = SomeDataSerializer
    filter_backends = [DjangoFilterBackend,]
    permission_classes = (AllowAny,)

    @action(methods=['GET'], detail=False, url_path='some_path')
    def any_function(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        result = any_function(args)
        return Response(result, status=status.HTTP_200_OK)

Any function is defined as:

def any_function(args):
    ...
    do something with args here and save it as result.
    ...
    return result

This works very smoothly and I don't have any problem here. BUT can I do something like this:

def any_function(args):
    result = some processing of args
    next_result = another processing of args
    return result, next_result

And still, get the response in the API endpoint but now for two different data. Also what if the result and next_result are two different JSON objects?

Anjaan
  • 595
  • 5
  • 19
  • Put both in a list, whose equivalent in json is an array. So you can send them as an array to the client. – Abdul Aziz Barkat Feb 26 '21 at 05:19
  • Should I do this in the function outside the viewset or inside? Also Will I be able to extract those results separately using JS in the frontend? – Anjaan Feb 26 '21 at 05:21
  • Your second example of `any_function` is fine even a tuple would be turned into an array when serializing to json. You can simply access both objects by indexing like you normally index in JavaScript. – Abdul Aziz Barkat Feb 26 '21 at 05:24
  • Ok Thanks, I'll try that. – Anjaan Feb 26 '21 at 05:26

2 Answers2

0

You should send them as an array:

How to Return an array of objects in a Django model

You can then interact with the array on the frontend.

Cyrus
  • 613
  • 1
  • 6
  • 22
0

You can make a list and then send as many responses as you want. for example:

def any_function(args):
    data   = []
    result1 = some processing of args
    result2 = another processing of args
    result3 = some other prossesed response
    data.append(result1)
    data.append(result2)
    data.append(result3)
    return data

It will send a list of responses.

You can also give name to every response using dictionary, for example:

data.append({"result1":result1})
return data

By giving a name to the different responses you will know the behavior of the response at the time of deserialization.