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.