Search through multiple fields in Django

前端 未结 4 1908
栀梦
栀梦 2021-01-03 00:47

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 unab

4条回答
  •  忘掉有多难
    2021-01-03 01:50

    As Robin Nemeth suggested, if you are using postgres db, can use the SearchVector, (I'm just making it straight to the question, get full details in django documentation.)

    First add django.contrib.postgres to the INSTALLED_APPS, helps leveraging PostgreSQL’s full text search engine.

    in the views.py of the search,

    from django.contrib.postgres.search import SearchVector
    
    
    # view function
    def hup_find(request):
      search_vector = SearchVector('name', 'state', 'city')
    
      if ('q' in request.GET) and request.GET['q'].strip():
        query_string=request.GET['q']
        seens = Findhall.objects.annotate(
                    search=search_vector).filter(search=query_string)
    
      return render(request, 'find.html', {'seens':seens})
    

    For large databases the search process takes some time, you can improve the performance using use GIN-(Generalized Inverted Index) feature of postgresql, These are some helpful links other than the official documentation,

    • Mastering django Search.
    • This stackoverflow question.

    There is different approach found, I think employing search in a more pythonish way by Julien Phalip,

提交回复
热议问题