【发布时间】:2016-02-01 08:41:46
【问题描述】:
我正在尝试在我的网站上创建一个搜索优化器来过滤关键字,问题是有时人们可能想要搜索多个关键字。问题是默认情况下,如果他们输入“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)
编辑: 我被要求解释为什么这篇文章是独一无二的,另一个问题是询问如何将他的查询与他的所有模型字段进行比较。这是询问如何从单个字段中过滤多个关键字。
【问题讨论】:
-
How to get more than one field with django filter icontains 的可能重复项。它不完全相同,但本质上是:手动循环。