我正在尝试在我的网站上进行过滤关键字的搜索精简程序,问题是有时候人们可能想要搜索多个关键字。问题是默认情况下,如果他们输入“hello world”,它会搜索完整的短语,但我希望它将它分开,以便搜索“hello”和“world”。到目前为止,我已将.split()
添加到关键字,并将它分开,但它阻止了我在查询中使用__icontains
。任何人都可以提出最好的方法来做到这一点?干杯!过滤多个关键字
代码 -
def browse(request):
business_industry = request.GET.get('business_industry', '')
business_address_region = request.GET.get('business_address_region', '')
employment_type = request.GET.get('employment_type', '')
pay_rate = request.GET.get('pay_rate', '')
keywords = request.GET.get('keywords', '').split()
form = JobSearchForm(initial=request.GET)
filters = Q(active_listing=True)
if business_industry:
filters &= Q(business_industry=business_industry)
if business_address_region:
filters &= Q(business_address_region=business_address_region)
if employment_type:
filters &= Q(employment_type=employment_type)
if pay_rate:
filters &= Q(pay_rate=pay_rate)
if keywords:
filters &= Q(job_description__icontains=keywords) | Q(job_title__icontains=keywords)
job_listings = JobListing.objects.filter(filters).distinct().order_by('-listing_date')
context_dict = {
'joblistings': job_listings,
'form': form
}
return render(request, 'browse.html', context_dict)
编辑: 我被要求解释为什么这个帖子是独一无二的,其他的问题是询问如何查询自己比较他所有的模型字段。这是要求如何从单个字段过滤多个关键字。
的可能的复制[如何获得Django的过滤器icontains多个字段(http://stackoverflow.com/questions/15045101/如何对获得-更比一个场与 - Django的过滤icontains)。它不完全相同,但本质上是:手动循环。 – dhke