1

如何添加到我的搜索视图中,还可以选择按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))
4

1 回答 1

2

你可以做:

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

这是有关跨越关系的查找的相关文档

于 2013-06-27T14:06:06.970 回答