-3

我有简单的搜索应用程序我如何按类别搜索使用<select><option></select>

结果 :

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>
4

1 回答 1

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) 
于 2012-11-12T20:28:34.620 回答