首页 > 解决方案 > 将查询参数作为字典传递,在邮递员中有许多值

问题描述

我正在使用postman我的 API。我有一个关于通过 postman 发送查询参数的问题params。在我的 API 中,我使用参数获取参数services = request.GET.get('services'),然后返回服务响应。

我的问题是,如果有多个服务,如“A”、“B”、“C”,那么我们如何使用邮递员在参数中发送这些服务?

视图.py

class SomeAPIView(ModelViewSet):
    def get_queryset(self):
        services = self.request.GET.get('services')
        print(services)            # getting  services
        print(type(services))      #type is string
        response_list = []
        for service in services:
            result = API(service=service)
            response_list.append(result)
        return response_list

我想要获取服务列表,然后遍历该列表以返回该服务的响应。

标签: djangopython-3.xpostman

解决方案


这取决于您将如何在生产中使用此 API 条目。

一开始,django中的好方法是使用request.query_params获取查询参数。get()如果没有传递“服务”参数,您还必须为方法提供默认值以避免异常。

然后,如果您的 services 参数包含某些对象的名称或 id,您可以在 GET 请求中将其与参数一起传递为http://someurl?services=A,B,C,或在选项卡中,在邮递员中命名为“Params”。所以request.query_params.get('sevices', '')将返回字符串,包含'A,B,C'。现在你可以用 ',' 来分割它,比如services_names = str.split(',').

无论如何,GET 请求的参数可能只返回str值。

根据您的示例,它可能如下所示:

class SomeAPIView(ModelViewSet):
    def get_queryset(self):
        services = self.request.query_params.get('sevices', '').split(',')
        print(services)            # getting  services
        print(type(services))      # now it will be List[str]
        response_list = []
        for service in services:
            result = API(service=service)
            response_list.append(result)
        return response_list

推荐阅读