Django searches the page and solves the "related field has invalid lookup: icontains" error.

Source: Internet
Author: User

Django version 1.4.5

Generally, websites require the search box, And my projects also need it.

First, write the view

1 # this is not my project. Just use it as an example to Solve the Problem 2 from Django. DB. models import Q 3 from models import Book 4 5 def search (request): 6 query = request. get. get ('Q', '') 7 if query: 8 qset = (9 q (Title _ icontains = query) | 10 Q (authors _ first_name _ icontains = query) | 11 Q (authors _ last_name _ icontains = query) 12) 13 # note the above fields, they are all one-to-one 14 # In models, but in my project, author is a foreign key. Therefore, if there are 15 # non-one-to-one fields, an error will occur, solution: 16 Results = book. objects. filter (qset ). distinct () 17 else: 18 results = [] 19 Return render_to_response ("Books/search.html", {20 "Results": Results, 21 "query": query22 })
Views. py

In the view, pay attention to the type after Q. If it is not one-to-one, an error will occur and needs to be modified. The solution is described later.

Also, pay attention to double underscores

Next, write the front-end code.

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">  2 Search.html

Simple code is mainly used for learning. Note that escape is used for escape to prevent security problems caused by some special characters.

Because author is a foreign key in my project, the related field has invalid lookup: icontains error occurs using the above method.

Because the author field is not one-to-one, it is automatically associated with its own ID, that is, its own primary key, which is messy.

So an error occurred.

Solution: Write the original code as Q (author _ name _ icontains = query)

To explain, author is a table and name is a field. Note the connection mode (Double underline). In this way, the name is searched.

Django searches the page and solves the "related field has invalid lookup: icontains" error.

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: info-contact@alibabacloud.com 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.