【发布时间】:2018-12-04 11:55:33
【问题描述】:
我们正在尝试返回 Django API 的标题列表,其中标题可以包含几个关键字。
例如,如果我们使用__icontains 方法搜索“money”和“world” (api.com/?keyworld=money&keyword=world),这将返回所有包含 money、world 或两者的记录。
相关的SQL语句为:
select * from news
where news_source = 1 or news_source = 2
and news_title like '%money%' or news_title like '%world%'
我们正在尝试使用此代码来允许用户拥有多个__icontains 的关键字以及多个来源,因此最终目标是:
api.com/?keyworld=money&keyword=world&source=1&source=2
我们的代码:
def get_queryset(self):
queryset = News.objects.all()
title = self.request.query_params.getlist('title')
source = self.request.query_params.getlist('source')
if title:
queryset = queryset.filter(news_title__icontains=title, news_source__in=source)
return queryset
问题在于,如果使用第二个关键字,这只会返回第二个关键字,而不是在&keyword= 中键入的内容之前的其他关键字。
【问题讨论】:
-
在获取参数中您使用
keyworld,但在过滤器getlist('title')中是否正确?并请显示数据示例。
标签: python django python-3.x django-rest-framework