Django blog simple full-text search

Author: HelloGitHub- Dream figure

Sample code files involved, synchronized to the updating HelloGitHub-Team warehouse

Search is a complex function, but for some simple search task, we can use some built-in methods Django Model layer provided to complete. Now we offer a simple search function for our blog.

Outline

Blog article usually contains the title and body of two parts. When users enter a keyword to search, we want the user to display the title and body text contains the search keywords of all articles. Search the whole process is as follows:

  1. Users in the search box keyword search elements, assumed to be "django", then the user clicks the search button to submit the results of their input to the server.
  2. Server receives user input search keywords after "django" database to find all the articles contained in the body of the article title and the keyword.
  3. The server returns the query results to the user.

The whole process is so, let's look at how to use Django implement these processes.

Keywords will be submitted to the server

Our first look at Django's blog Post (article) model:

blog/models.py

class Post(models.Model):
    # 标题
    title = models.CharField("标题", max_length=70)
    # 正文
    body = models.TextField("正文")
    
    # 其他属性...
    
    def __str__(self):
        return self.title

To see the first step, the user enters a search keyword in the search box, so we want to provide users with a search form on the blog, HTML form code that went something like:

templates/base.html

<form role="search" method="get" id="searchform" action="{% url 'blog:search' %}">
  <input type="search" name="q" placeholder="搜索" required>
  <button type="submit"><span class="ion-ios-search-strong"></span></button>
</form>

Special attention here <input type="search" name="q" placeholder="搜索" required>name attribute, when users type a search using the input and submit the form, type of data will be submitted to the server in the form of key-value pairs, the name of this key is specified by the name attribute. So that the server can obtain user input based on the value of name.

After the user enters a keyword search and click on the search button, the data is sent to the Django backend server. Form actionis {% url 'blog: search' %} attribute (Although we have not write this view function), the result indicates that the user submit to be transmitted to the blog search application view function corresponding URL.

Find articles containing search keywords

The search function will provide search view function, the code is written in the blog / views.py in:

blog/views.py

from django.contrib import messages

def search(request):
    q = request.GET.get('q')

    if not q:
        error_msg = "请输入搜索关键词"
        messages.add_message(request, messages.ERROR, error_msg, extra_tags='danger')
        return redirect('blog:index')

    post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))
    return render(request, 'blog/index.html', {'post_list': post_list})

First, we use request.GET.get('q')the acquired user-submitted search keywords. Data submitted by the user get method Django form as we save request.GET, this is similar to an object Python dictionary, so we use geta method taken from the key value q corresponding to the dictionary, i.e., the user's search keywords. Here dictionary was called q is key because the value of the name attribute of our form in the search box input is q, if you modify the value of the name attribute, then the name of the key should be amended accordingly.

Then we did a little checking, if the user does not enter search keywords and submit the form, we do not need to execute the query, we send the user to give an error message reminder, here using the django messages application, which in exchange bridge: comment feature in spoken. Then the user is redirected to the home page. Here's redirect function is also spoken in that tutorial.

If the user enters a keyword search, we pass filterfiltering method from the database all the articles eligible. The filtering criteria are here title__icontains=q, that title is included (the contains) the keyword q, i represents the prefix is not case sensitive. Here icontainsis a query expression (Field lookups), before we have used other similar query expression, its use is in keeping with two underscores after the property model to be screened. Django built a lot of query expressions, it is recommended to go over the official Django looks, and understand the role of each expression, after the encounter related needs can quickly navigate to the query document its use Field, Lookups .

In addition, we introduced here a new thing from from django.db.models in: Q object. Q query expression for packaging an object, its role is to provide a complex query logic. Here, for example, Q(title__icontains=q) | Q(body__icontains=q)represents a title (title) q contain the keyword or text (body) that contain the keyword q, logic, or using |symbols. If you do not have Q object can only be written title__icontains=q, body__icontains=q, it becomes headline (title) q contain keywords and text (body) that contain the keyword q, it is not the purpose of what we want.

Binding URL

With the rear view function remember to map view function corresponding to the URL, as follows.

blog/urls.py

urlpatterns = [
    # 其他 url 配置
    path('search/', views.search, name='search'),
]

Done in the navigation bar to try to enter some keywords and see the effect it!

Of course, this search function is very simple, it is difficult to meet some complex search requirements. Writing a search engine is a big project, but fortunately django-haystack this third-party app to complete all the work for us. With it we can achieve a more sophisticated search features, such as full-text search, sorted by search relevance, keyword highlighting, and so similar to the function of Baidu search function is very powerful. Of course, it will be complicated to use, next tutorial will introduce django-haystack combined use Elasticsearch search engine.


"Explain open source projects Series" - to let people interested in open source projects are no longer afraid, let sponsors open source projects are no longer alone. Follow our articles, you'll discover the fun of programming, the use of open source projects and found to be involved so simple. Welcome messages to contact us, join us, so that more people fall in love with open source, open source contribution ~

Guess you like

Origin www.cnblogs.com/xueweihan/p/12171812.html