Django Learning-How to implement a simple search function

Source: Internet
Author: User

The implementation of the search function is that the user enters the content to be searched on the front page, then passes through the URL to the backend, the backend view function finds out the specified object from the database, and then passes the procedure to the front page.

Here we mainly talk about the lookup process in the View function:

From django.db.models import Q

#url to

def MyApp (request):
    if Request.method = = ' GET ':
        keywords = Request. Get.get (' keywords ', ')  #得到搜索关键词 ' Django '
        course_list = Course.objects.filter (Q (name__icontains=keywords) | Q (detail__icontains=keywords))
        return render (Request, ' course-list.html ', {' course_list ': course_list})

This is where Name__icontains gets the object containing keywords in name, and for more usage of object_filter (), see my previous blog: objects.filter () usage

Using the Q () method to implement multiple query conditions, for more information about Q (), see my previous blog: using the Q () method for querying

And in the front-end code implementation, mainly through the JS code to achieve click Search function, here no longer repeat (in fact, I will not-_-), the code is as follows:

//Top Search Bar Search method function Search_click () {var type = $ (' #jsSelectOption '). attr (' Data-value '),
    Keywords = $ (' #search_keywords '). Val (), Request_url = "; 
    if (keywords = = "") {return} if (type = = "Course") {Request_url = "/course/list?keywords=" +keywords }else if (type = = "Teacher") {Request_url = "/org/teacher/list?keywords=" +keywords}else if (type = = "org") {Request_url = "/org/list?keywords=" +keywords} window.location.href = Request_url} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.