2012-11-12 66 views
-3

我有簡單的搜索應用 我如何可以通過使用<select><option></select>按類別列表搜索 - Django的

結果分類 搜索:

results = Adv.objects.filter(title__icontains=query).filter(cate__name__icontains=query) 

這裏是代碼:

車型

class Category(models.Model): 
    slug = models.SlugField(unique=True) 
    name = models.CharField(max_length=60) 

class Adv(models.Model): 
    title = models.CharField(max_length=60) 
    pub_date = models.DateTimeField(auto_now_add=True) 
    namecar = models.CharField(max_length=60) 
    cate = models.ForeignKey(Category) 

鑑於

def search(request): 
    if 'q' in request.GET: 
     query = request.GET['q'] 
     results = Adv.objects.filter(title__icontains=query).filter(cate__name__icontains=query) 
    # print results.query 
    else: 
     query = "" 
     results = None 
    template = loader.get_template('search/search1.html') 
    context = Context({ 'query': query, 'results': results, 'city_list': ChoiceCity.objects.all() }) 
    response = template.render(context) 
    return HttpResponse(response) 

網址

(r'^search1/$', 'car.search.views.search'), 

模板

<form method="get" action="/search1/"> 
<p><label for="id_q">Search:</label> 
<input type="text" name="q" id="id_q" value="{{ query }}" /> 
<input type="submit" value="Submit" /></p> 
</form> 
+1

您的問題到底是什麼? –

+0

我要讓高級搜索,並通過分類列表 ,對不起我的英文不好 –

+0

我添加了一個答案,請看看,讓我知道如果你 –

回答

1

我猜你希望能夠過濾基於類別的結果。我會建議在模板中添加一個類別選擇下拉菜單。這將需要您將類別對象發送到模板中,以便它可以呈現

<form method="get" action="/search1/"> 
<p><label for="id_q">Search:</label> 
<input type="text" name="q" id="id_q" value="{{ query }}" /> 
<select name="category"> 
    {% for category in categories %} 
    <option value="{{category.id}}">{{category.name}}</option> 
    {% endfor %} 
</select> 
<input type="submit" value="Submit" /></p> 
</form> 



def search(request): 
     if 'q' in request.GET: 
      #Get the selected category id 
      sel_category = request.GET.get('category', None) 
      #If it exists, get the category object 
      if sel_category: 
       category = get_object_or_404(Category, pk = sel_category) 
      query = request.GET['q'] 
      results = Adv.objects.filter(title__icontains=query) 
      #If category objects exists filter the result set based on that 
      if category: 
        results =results.filter(cate__name__icontains=category.name) 
     # print results.query 
     else: 
      query = "" 
      results = None 
      categories = Category.objects.all() 
     template = loader.get_template('search/search1.html') 
     context = Context({ 'query': query, 'results': results, 'city_list': ChoiceCity.objects.all(), 'categories':categories }) 
     response = template.render(context) 
     return HttpResponse(response) 
+0

非常感謝你的幫助 –

+0

最後一個問題,任何問題 我如何在