Skip to main content
 首页 » 编程设计

python之过滤多个关键词

2025年05月04日30oomusou

我正在尝试在我的网站上制作一个过滤关键字的搜索优化器,问题是有时人们可能想要搜索多个关键字。问题是默认情况下,如果他们输入“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) 

编辑: 我被要求解释为什么这篇文章是独一无二的,另一个问题是询问如何将他的查询与他的所有模型字段进行比较。这是在询问如何从单个字段中过滤多个关键字。

请您参考如下方法:

你可以使用 Reduce 函数:

reduce(lambda x, y: x | y, [Q(name__icontains=word) for word in list]) 

更改此代码:

if keywords: 
    filters &= Q(job_description__icontains=keywords) | Q(job_title__icontains=keywords) 

收件人:

if keywords: 
    fliters &= reduce(lambda x, y: x | y, [Q(job_description__icontains=word) for word in keywords]) | reduce(lambda x, y: x | y, [Q(job_title__icontains=word) for word in keywords]) 

您可以根据需要更改 lambda 定义。例如,如果您想查找包含所有关键字的列表,请替换 lambda x, y: x | y 与 lambda x, y: x & y。

编辑: 修改代码,因为有两个不必要的括号