在Django中搜索多个字段 [英] Search through multiple fields in Django
问题描述
我正在尝试建立一个搜索系统,我想在Django模型中按多个字段名称,州,城市,
进行搜索。我编写了以下代码,但我一直无法弄清楚该怎么做。
I'm trying to build a search system, and I want to search by multiple fieldsname, state, city,
in my django models. I wrote the below code, yet I've been unable to figure out how to go about it.
模型:
class Finhall(models.Model):
user=models.ForeignKey(User)
name=models.CharField(max_length=250, unique=True)
address=models.CharField(max_length=200)
city=models.CharField(max_length=200)
state=models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.name)
Views.py
def hup_find(request):
if ('q' in request.GET) and request.GET['q'].strip():
query_string=request.GET.get('q')
seens=Finhall.objects.filter(name__icontains=query_string)
else:
seens=None
return render_to_response('find.html',{'seens':seens},context_instance=RequestContext(request))
模板:
{% block content %}
<body>
<form action="" method="GET">
<input type="text" name="q" />
<button type="submit">search</button>
</form>
{% for seen in seens %}
<p> {{seen.name}}</p>
{% empty %}
<p> no search </p>
{% endfor %}
</body>
{% endblock %}
我该怎么办?由于某些个人原因,我不想使用haysatck。
How can I go about this? I don't want to use haysatck due to some personal reasons.
推荐答案
您可以使用django Q
对象以进行或
查询,
you can use django Q
objects to do OR
query,
或如果要 AND
您的查询一起只是将当前的查询用作warps
or if you want to AND
your queries together just use the current lookups as kwargs
seens = Finhall.objects.filter(
name__icontains=query_string,
address__icontains=query_string
)
真正考虑全文搜索或干草堆
(这使搜索变得容易),因为包含会产生
% LIKE%
不能远程扩展
You should really consider full text search or haystack
(which makes search easy) because icontains
issues a %LIKE%
which is not remotely scalable
这篇关于在Django中搜索多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!