django - 将查询参数作为字典传递,在邮递员中有许多值
问题描述
我正在使用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
我想要获取服务列表,然后遍历该列表以返回该服务的响应。
解决方案
这取决于您将如何在生产中使用此 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
推荐阅读
- asp.net - 如何在 PostgreSQL 中返回两个表
- dax - 计算一个表中列的不同值过滤表格模型DAX中的其他表
- python - 如何从python中记录的跳过
- android - 构建/生成文件夹中的清单类消失
- c - 如何释放指向整数数组的指针
- javafx - 将 HBox 设置为 TitledPane 的标题
- jquery - 如何更改底层元素的“src”属性
- mysql - Xampp MySQL 服务器未运行或被防火墙阻止
- c# - 使用 WEB API HttpClient 使用外部 API 然后以角度显示反序列化结果是否可以接受?
- xades4j - xades 的不同命名空间:QualifyingProperties