2016-01-24 171 views
1

如何查詢數據庫中的Django包含多個關鍵字搜索功能的Django項目實施

我有具有類這樣

class Job(models.Model): 
title = models.CharField(max_length=100) 

我想查詢jobs_job數據庫實現一個工作模型搜索功能使得

def search(request): 
if request.method == "GET": 
    search_terms = request.GET['title'] 
    search_terms = search_terms.split(',') 

    jobs = Job.objects.filter(title__contains=search_terms[0]) 

問題是我只能一項傳遞給contains方法,

我搜索使用多個單詞的作業模式標題怎麼辦屬性

回答

1

例如,你可以做

from django.db.models import Q 

def search(request): 
    if request.method == "GET": 
     search_terms = request.GET['title'] 
     search_terms = search_terms.split(',') 
     #get rid of duplicates 
     search_terms = set(search_terms) 
     queryargs = [Q(title__contains=i) for i in search_terms] 
     jobs = Job.objects.filter(*queryargs) 
+0

好吧,看起來很酷 – shining

+0

請參閱我的編輯,我已經使用了你的變量名稱並根據你的分隔符清理了一些東西',' – Pynchia

1

使用django.db.models.Q對象。就像這樣:

from django.db.models import Q 

def search(request): 
    if request.method == "GET": 
     search_terms = request.GET['title'] 
     search_filter = Q() 
     for term in search_terms.split(','): 
      search_filter |= Q(title__contains=term) 

     jobs = Job.objects.filter(search_filter) 

這將搜索任何條款(OR)的,要搜索的所有術語(AND)使用search_filter &= Q(title__contains=term)代替。