gpt4 book ai didi

Django过滤器: multiple IDs in a single query string

转载 作者:行者123 更新时间:2023-12-04 05:53:57 25 4
gpt4 key购买 nike

使用django-filters,我看到了各种解决方案,这些解决方案涉及如何在单个查询字符串中提交相同类型的多个参数,例如,多个ID。他们都建议使用一个单独的字段,其中包含用逗号分隔的值列表,例如:

http://example.com/api/cities?ids=1,2,3

是否存在使用单个参数但提交一次或多次的通用解决方案?例如。:
http://example.com/api/cities?id=1&id=2&id=3

我尝试使用 MultipleChoiceFilter ,但是它希望定义实际的选择,而我想传递任意ID(其中一些ID甚至可能在数据库中不存在)。

最佳答案

使用自定义过滤器解决了这个问题,灵感来自Jerin的答案:

class ListFilter(Filter):
def filter(self, queryset, value):
try:
request = self.parent.request
except AttributeError:
return None

values = request.GET.getlist(self.name)
values = {int(item) for item in values if item.isdigit()}

return super(ListFilter, self).filter(queryset, Lookup(values, 'in'))

如果值是非数字的,例如 color=blue&color=red,那么当然不需要 isdigit()验证。

关于Django过滤器: multiple IDs in a single query string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com