Django 3 by example学习 第三章 建搜索引擎

安装见这里:

http://www.jichangqing.net/wordpress/?p=274

setting.py中数据库设

DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'blog',
'USER': 'blog',
'PASSWORD': 'password', #建表时设置的密码
    }
}

数据迁移

python manage. py migrate

创建admin用户

python manage. py createsuperuser

INSTALLED_APPS = [
#...
'django.contrib.postgres',
#...
]

创建admin用户

forms.py

class SearchForm(forms.Form):
query = forms.CharField()

views.py

from .forms import EmailPostForm, CommentForm, SearchForm
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank, TrigramSimilarity
def post_search(request):
form = SearchForm()
query = None
results = []
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
#一般查询
# results = Post.published.annotate(
            #     search = SearchVector('title', 'body'),
            # ).filter(search=query)
search_vector = SearchVector('title', weight='A') + \
                            SearchVector('body', weight='B')
search_query = SearchQuery(query)
#近似查询和权值rank
# results = Post.published.annotate(
            #     search=search_vector, rank=SearchRank(search_vector, search_query)
            # ).filter(rank__gte=0.3).order_by('-rank')
# trigram相拟查询
results = Post.published.annotate(
similarity=TrigramSimilarity('title', query),
            ).filter(similarity__gt=0.1).order_by('-similarity')
return render(request,
'blog/post/search.html',
                  {'form':form,
'query': query,
'results': results,
                  }
                  )

url中path

path('search/', views.post_search, name='post_search'),

模板层 search.html

{% extends 'blog/base.html' %}
{% load blog_tags %}

{% block title %} Search {% endblock %}

{% block content %}
    {% if query %}
        <h1>Posts containing {{ query }}</h1>
        <h3>
            {% with results.count as total_results %}
                Found {{ total_results }} result {{ total_results|pluralize }}
            {% endwith %}
        </h3>
        {% for post in results %}
            <h4><a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </h4>
            {{ post.body|markdown|truncatewords_html:5 }}
        {% empty %}
            <p>There are no results for your query.</p>
        {% endfor %}
        <p><a href="{% url 'blog:post_search' %}">Search again</a> </p>
    {% else %}
    <h1>Search for posts</h1>
    <form method="get">
        {{ form.as_p }}
        <input type="submit" value="Search">
    </form>
    {% endif %}
{% endblock %}

其它扩展:

Haystack https: //django-haystack.readthedocs.io/en/master/

梦翔儿,根据2020年第3版英文书完成并记录。

原文链接:,转发请注明来源!
评论已关闭。