【问题标题】:Adding a simple search to a Django app向 Django 应用程序添加简单搜索
【发布时间】:2013-01-09 16:51:23
【问题描述】:

所以我正在关注this 教程以搜索我的一些模型。但是,对于所提供的内容缺乏文档,作为 Django 的新手,我很困惑为了完成这项工作而缺少什么。

这就是我所拥有的:

编辑

修改了搜索模板以包含一个用于获取查询的输入字段。

myproject.templates.search.html:

<form action="" method="get">
<label for="id_q">Search:</label>
<input id="id_q" name="q" type="text">
<input type="submit" value="Submit">

{% if found_entries %}
    <p>You searched for "{{ query_string }}".</p>
    <ul>
        {% for i in found_entries %}
            {{ i.uid }} {{ i.title }} {{ value|linebreaks }}
        {% endfor %}
    </ul>
{% endif %}

{% if query_string and not found_entries %}
    <p>No results found.</p>
{% else %}
    <p>Type a search query into the box above, and press "Submit" to search.</p>
{% endif %}

</form>

myapp.models.py:

from django.db import models

class Book(models.Model):
    uid = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=30)
    class Meta:
        db_table = u'books'

myapp.search.py​​:

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):
''' Splits the query string in invidual keywords, getting rid of unecessary spaces
    and grouping quoted words together.
    Example:

    >>> normalize_query('  some random  words "with   quotes  " and   spaces')
    ['some', 'random', 'words', 'with quotes', 'and', 'spaces']

'''
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

myapp.views.py:

from myapp.models import Book
from django.shortcuts import render_to_response
from django.template import RequestContext

def search(request):
    query_string = ''
    found_entries = None
    search_fields=('uid')

    if ('q' in request.GET) and request.GET['q'].strip():

        query_string = request.GET['q']

        entry_query = get_query(query_string, search_fields)

        found_entries = Book.objects.filter(entry_query)

        return render_to_response('search.html',
                         { 'query_string': query_string, 'found_entries': found_entries },
                         context_instance=RequestContext(request))

myproject.templates.search.html:

{% if found_entries %}
    <p>You searched for "{{ query_string }}".</p>
    <ul>
    {% for i in found_entries %}
        <li><a href="{{ q.get_absolute_url }}">{{ found_entries }}</a></li>
    {% endfor %}
    </ul>
{% endif %}
{% if query_string and not found_entries %}
    <p>No results found.</p>
{% else %}
    <p>Type a search query into the box above, and press "Submit" to search.</p>
{% endif %}

myproject.urls.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
url(r'^predictor/$', 'myapp.views.search'),
)

如果我去:http://localhost:8000/myapp/

图片:http://i.imgur.com/QFaWZ.png

谢谢!

【问题讨论】:

标签: python django forms postgresql search


【解决方案1】:

您的模板中没有表单:您从未在页面上放置搜索框,为什么要显示?

看看django documentation on using forms


这将需要大量的工作,但您没有使用 Django 的任何内置机制来创建表单。这样做将使您的代码更清晰(并且会更容易!)。

【讨论】:

    【解决方案2】:

    如果您查看您的代码(我鼓励您这样做),您正在查看的视图是 myapp.views.search 对吗?查看您的搜索功能,您应该能够看到它在 request.GET 中查找 'q' 键,这相当于从查询字符串中获取 'q' 元素,因此它就是从中获取搜索的地方。

    所以要搜索你会去http://localhost:8000/myapp/?q=searchterm 'searchterm' 是指你正在搜索的词。

    就像 thomas 所说,虽然您可能也想创建一个表单来使用此功能。

    【讨论】:

    • 是的,看起来更好,如果你发现自己重用了这个表单,你也可以编写一个 django 表单来做同样的事情,但是你正在做的似乎很好。
    猜你喜欢
    • 2017-09-02
    • 2010-12-18
    • 2010-10-24
    • 2023-03-23
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多