Search across multiple fields in Django

I am trying to create a search engine and I want to search several fields of name, state, city, in my django models. I wrote the code below, but I could not figure out how to do this.

Models:

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

Template:

  {% 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 %} 

How can i do this? I do not want to use haysatck for any personal reasons.

+4
source share
3 answers

you can use django Q objects to execute an OR request,

or if you want AND your queries together to use current queries like kwargs

seens=Finhall.objects.filter(name__icontains=query_string, address__icontains=query_string)

You should really consider a full text search or haystack (which simplifies the search), because icontains a %LIKE% , which cannot be remotely scalable

+4
source

EDIT: Just noticed that only Postgres

Apparently in django 1.10 SearchVector .

Use of documents:

A single-field search is large, but rather limited. Entry instances were found on a blog that has a tagline field. To query both fields, use SearchVector:

 >>> from django.contrib.postgres.search import SearchVector >>> Entry.objects.annotate( ... search=SearchVector('body_text', 'blog__tagline'), ... ).filter(search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>] 
+3
source

To search for the same text in multiple fields, you can use this:

 from django.db.models import Q class SearchAPI(APIView): def get(self, request, search_text, format=None, **kwargs): Model.objects.filter(Q(search_tags__contains=search_text) | Q(auto_tags__contains=search_text) 
0
source

All Articles