简体   繁体   English

有没有办法通过 django rest Z8A5DA52ED126447D359E70C05721A 返回多个 json 对象?

[英]Is there a way to return multiple json objects through django rest api?

I know, I can return a single object through Django viewsets for any method.我知道,对于任何方法,我都可以通过 Django 视图集返回单个 object。 But can I return multiple objects through the API?但是我可以通过 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:任何 function 定义为:

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.而且,在 API 端点中获得响应,但现在是两个不同的数据。 Also what if the result and next_result are two different JSON objects?另外,如果 result 和 next_result 是两个不同的 JSON 对象怎么办?

You should send them as an array:您应该将它们作为数组发送:

How to Return an array of objects in a Django model 如何返回 Django model 中的对象数组

You can then interact with the array on the frontend.然后,您可以与前端的数组进行交互。

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.通过为不同的响应命名,您将了解反序列化时响应的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM