使用Python / Django中的数据库查询在多列中搜索?

时间:2013-04-02 06:18:12

标签: django search

我有一个这样的模型:

class Info(models.Model):
    tape_id = models.TextField()
    name = models.TextField()
    video_type = models.TextField()
    date = models.DateTimeField()
    director = models.CharField(max_length=255)
    cameraman = models.CharField(max_length=255)
    editor = models.CharField(max_length=255)
    time_code = models.TextField()
    tag1 = models.TextField()

用户可以使用相同的搜索输入框从tape_id, name, director and cameraman进行搜索。 我有这样的搜索视图:

 if request.method == 'POST':
        search_inp = request.POST['search_box']
        tape_id = Info.objects.filter(tape_id__exact=search_inp)
        res = Info.objects.filter(name__icontains=search_inp)
        res = Info.objects.filter(director__icontains=search_inp)
        res = Info.objects.filter(cameraman__icontains=search_inp)
        total_video = res.count()
        if len(res) == 0 and len(tape_id) == 0 :
            result = "No videos found!!"
            return render_to_response('no_results_only.html', {'result':result}, context_instance=RequestContext(request))
        else:
            date1 = [i.date for i in res]
            date = [i.strftime("%B %d, %Y") for i in date1]
            a = zip(res, date)
            return render_to_response('list_videos.html', {'a':a, 'total_video':total_video}, context_instance=RequestContext(request))
        return HttpResponseRedirect('/')

我认为它最初会起作用,但事实并非如此。第一个res变量可以包含该值,而最后一个res为空,它将返回no_results.html。我想使用相同的输入框部署此搜索。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

首先,您需要导入Q以用于OR过滤:

from django.db.models import Q

然后你的代码应该是这样的:

if request.method == 'POST':
    search_inp = request.POST['search_box']
    res = Info.objects.filter(
        Q(tape_id__exact=search_inp) | 
        Q(name__icontains=search_inp) |
        Q(director__icontains=search_inp) |
        Q(cameraman__icontains=search_inp)
    )
    total_video = res.count()
    if len(res) == 0:
        result = "No videos found!!"
        return render_to_response('no_results_only.html', {'result':result}, context_instance=RequestContext(request))
    else:
        date1 = [i.date for i in res]
        date = [i.strftime("%B %d, %Y") for i in date1]
        a = zip(res, date)
        return render_to_response('list_videos.html', {'a':a, 'total_video':total_video}, context_instance=RequestContext(request))
    return HttpResponseRedirect('/')

答案 1 :(得分:0)

建议在OR中应用filter条件。您可以参考documentation获取语法。

Q(question__startswith='Who') | Q(question__startswith='What')

它将确保您在结果中获得唯一的对象列表。