如何添加到我的搜索视图,选择按类别名称搜索?

时间:2013-06-27 13:58:17

标签: django

如何添加到我的搜索视图,还可以按Category名称搜索选项?

模型:

class Document(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()

class Category(models.Model):
    name = models.CharField(max_length=255)
    document = models.ForeignKey(Document)

的观点:

def search(request):
    if 'search' in request.GET:
        term = request.GET['search']
        if len(term) > 5:
            d = Document.objects.filter(Q(title__contains=term) | Q(
                content__contains=term))
            count = d.count()
            return render_to_response('search_result.html', {'d': d,'term':term, 'count': count}, context_instance=RequestContext(request))
    return render_to_response('search_result.html', context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

你可以这样做:

d = Document.objects.filter(Q(title__contains=term) | Q(
            content__contains=term) | Q(category__name__contains=term))

以下是lookups that span relationships

的相关文档