我想根据用户输入从Django model(mysql)获取数据。就像我有一个html搜索选项卡一样,用户将在其中放置搜索值,该值应该从Django模型获取相关数据并显示在另一个html页面中。我试过但失败了.请帮忙..
views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse
from hello.models import Techstop
# Create your views here.
def search(request):
return render_to_response('search.html')
def results(request):
if 'q' in request.GET and request.GET['q']:
q=request.GET['q']
name=Techstop.objects.filter(City=q)
return render_to_response('results.html')
else:
return HttpResponse('Please enter a valid input.')
models.py
from django.db import models
class Techstop(models.Model):
Name = models.CharField(max_length=30)
Email = models.CharField(max_length=50)
City = models.CharField(max_length=20)
Country = models.CharField(max_length=20)
Dept = models.CharField(max_length=30)
def __unicode__(self):
return self.City
search.html
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
results.html
{% if name %}
<ul>
{% for n in name %}
<li>{{ n.City }}</li>
{% endfor %}
</ul>
{% else %}
<p>No name matched your search criteria.</p>
{% endif %}
假设您使用GET方法提交表单:
def results(request):
q = request.GET.get('q', None)
if q:
# icontains work similar to LIKE keyword in mysql.
# for exact text search you can directly search City=q
name=Techstop.objects.filter(City__icontains=q)
# {'name': name} is the context that we attach with the html to render.
return render_to_response('results.html', {'name': name})
else:
return HttpResponse('Please enter a valid input.')
您还可以使用 Q 对象进行更多 comples 搜索。
渲染任何模板时,您需要将其所需的所有变量作为上下文字典传递。
return render_to_response('results.html', {'name': name})
这一切都在教程中解释;你可能应该去遵循它。
您可以使用
以下函数简单地执行此操作:
import re
from django.db.models import Q
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(S+)').findall,
normspace=re.compile(r's{2,}').sub):
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
def get_query(query_string, search_fields):
''' Returns a query, that is a combination of Q objects. That combination
aims to search keywords within a model by testing the given search fields.
'''
query = None # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query
使用示例:
def search(request):
if request.method == 'GET':
if request.GET.get("submit_search_button"): # if search submit button clicked
query_string = ''
found_entries = None
if ('q' in request.GET) and request.GET['q'].strip():
query_string = request.GET['q']
entry_query = get_query(query_string, ['name', 'email','city','country','dept'])
found_entries = Techstop.objects.filter(entry_query)
return render_to_response('search.html',
{ 'query_string': query_string, 'found_entries': found_entries },
context_instance=RequestContext(request))
return HttpResponseNotAllowed('only GET here for example!!')
希望有帮助!!