Django搜索功能 - 长度为2的搜索查询的错误

时间:2009-12-23 15:48:02

标签: django search

由于我是Stack Overflow的一位印象深刻的读者,我想在这里问我的第一个问题。由于我遇到了代码片段的问题,我不知道我是犯了错误还是我正在使用的代码中的错误。

我为自己的网站修改了这段代码:

http://blog.tkbe.org/archive/django-admin-search-functionality/

它工作正常,它真的是一个很棒的片段。 但如果我的搜索查询长度为2,我认为结果不正确。

例如,如果我在名字和姓氏中搜索“re”,我会得到以下结果:

Mr. Tom Krem
Ms. Su Ker

这很奇怪。对于长度为>的查询2我没有遇到这个问题。 所以也许这篇文章读了一个使用上面代码片段的人,可以告诉我他/她是否遇到同样的问题。

如果没有其他人遇到问题,我至少知道我的代码中有错误。也许是我正在使用的形式,或者在请求上下文中搞砸了什么。

我该如何解决这个问题?

编辑1:

包含标记:

from django import template
from crm.views import SEARCH_VAR

def my_search_form(context):
    return {
        'context': context,
        'search_var': SEARCH_VAR
    }

register = template.Library()
register.inclusion_tag('custom_utilities/my_search_form.html')(my_search_form)

my_search_form.html

<div id="toolbar"><form 
      id="changelist-search" 
      action="" 
      method="get"> 
        <div><!-- DIV needed for valid HTML --> 
            <label 
              for="searchbar"><img src="{{ context.media_url }}/crm/img/search.png" 
              class="icon" 
              alt="Search" /></label> 
            <input 
              type="text" 
              size="40" 
              name="{{ search_var }}" 
              value="{{ context.query }}" 
              id="searchbar" /> 
            <input type="submit" value="Search" />
        </div>
    </form>
</div> 
<script 
  type="text/javascript">document.getElementById("searchbar").focus();
</script>

视图:

@login_required
def crm_contacts(request):
    query = request.GET.get('q', '')
    #pass additional params to the SortHeaders function
    #the additional params will be part of the header <a href...>
    #e.g. use it for pagination / use it to provide the query string
    additional_params_dict = {'q': query}
    foundContacts = search_contact(request,query)
    sort_headers = SortHeaders(request, LIST_HEADERS, default_order_field=1, additional_params=additional_params_dict)
    if foundContacts is not None:
        contact_list = foundContacts.order_by(sort_headers.get_order_by())
    else:
        contact_list = Contact.objects.order_by(sort_headers.get_order_by())
    context = {
        'contact_list' : contact_list,
        'headers': list(sort_headers.headers()),
        'query' : query,
    }
    return render_to_response("crm/contact_list.html", context,
                           context_instance=RequestContext(request))

联系人搜索表单:

#models
from crm.models import Contact
from django.db.models import Q

'''
A search form from
http://blog.tkbe.org/archive/django-admin-search-functionality/
adapted to search for contacts.
'''
def search_contact(request,terms=None):
    if terms is None:
        return Contact.objects.all()
    query = Contact.objects
    for term in terms:
        query = query.filter(
            Q(first_name__icontains=term)
            | Q(last_name__icontains=term))
    return query

另一个编辑:

我正在使用此代码段对表格进行排序。可能应该知道这一点,以便理解上面发布的代码。

由于我无法发布链接(垃圾邮件防护),我将尝试解释在哪里找到它。转到Google。输入:django snippet table sort

然后它应该是第二击。排序表标题。代码片段308。

编辑:添加SortHeaders()函数

ORDER_VAR = 'o'
ORDER_TYPE_VAR = 'ot'

class SortHeaders:
    """
    Handles generation of an argument for the Django ORM's
    ``order_by`` method and generation of table headers which reflect
    the currently selected sort, based on defined table headers with
    matching sort criteria.

    Based in part on the Django Admin application's ``ChangeList``
    functionality.
    """
    def __init__(self, request, headers, default_order_field=None,
            default_order_type='asc', additional_params=None):
        """
        request
            The request currently being processed - the current sort
            order field and type are determined based on GET
            parameters.

        headers
            A list of two-tuples of header text and matching ordering
            criteria for use with the Django ORM's ``order_by``
            method. A criterion of ``None`` indicates that a header
            is not sortable.

        default_order_field
            The index of the header definition to be used for default
            ordering and when an invalid or non-sortable header is
            specified in GET parameters. If not specified, the index
            of the first sortable header will be used.

        default_order_type
            The default type of ordering used - must be one of
            ``'asc`` or ``'desc'``.

        additional_params:
            Query parameters which should always appear in sort links,
            specified as a dictionary mapping parameter names to
            values. For example, this might contain the current page
            number if you're sorting a paginated list of items.
        """
        if default_order_field is None:
            for i, (header, query_lookup) in enumerate(headers):
                if query_lookup is not None:
                    default_order_field = i
                    break
        if default_order_field is None:
            raise AttributeError('No default_order_field was specified and none of the header definitions given were sortable.')
        if default_order_type not in ('asc', 'desc'):
            raise AttributeError('If given, default_order_type must be one of \'asc\' or \'desc\'.')
        if additional_params is None: additional_params = {}

        self.header_defs = headers
        self.additional_params = additional_params
        self.order_field, self.order_type = default_order_field, default_order_type

        # Determine order field and order type for the current request
        params = dict(request.GET.items())
        if ORDER_VAR in params:
            try:
                new_order_field = int(params[ORDER_VAR])
                if headers[new_order_field][1] is not None:
                    self.order_field = new_order_field
            except (IndexError, ValueError):
                pass # Use the default
        if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
            self.order_type = params[ORDER_TYPE_VAR]

    def headers(self):
        """
        Generates dicts containing header and sort link details for
        all defined headers.
        """
        for i, (header, order_criterion) in enumerate(self.header_defs):
            th_classes = []
            new_order_type = 'asc'
            if i == self.order_field:
                th_classes.append('sorted %sending' % self.order_type)
                new_order_type = {'asc': 'desc', 'desc': 'asc'}[self.order_type]
            yield {
                'text': header,
                'sortable': order_criterion is not None,
                'url': self.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}),
                'class_attr': (th_classes and ' class="%s"' % ' '.join(th_classes) or ''),
            }

    def get_query_string(self, params):
        """
        Creates a query string from the given dictionary of
        parameters, including any additonal parameters which should
        always be present.
        """
        params.update(self.additional_params)
        return '?%s' % '&amp;'.join(['%s=%s' % (param, value) \
                                     for param, value in params.items()])

    def get_order_by(self):
        """
        Creates an ordering criterion based on the current order
        field and order type, for use with the Django ORM's
        ``order_by`` method.
        """
        return '%s%s' % (
            self.order_type == 'desc' and '-' or '',
            self.header_defs[self.order_field][1],
        )

1 个答案:

答案 0 :(得分:0)

如果您运行manage.py shell,然后运行:

>>> from crm.models import Contact
>>> from django.db.models import Q
>>> list=Contact.objects.filter(Q(first_name__icontains='re')|Q(last_name__icontains='re'))
>>> print list

输出是什么?


编辑:是的,所以如果你尝试:

>>> list=Contact.objects.filter(Q(first_name__icontains='mot')|Q(last_name__icontains='mot'))
>>> print list

(我正试图缩小给你问题的条款,我看到了你的上一条评论)

输出是什么?


编辑:如果以上两个查询都在shell中工作,那么其他东西正在某处修改您的查询集并添加一些额外的标准......

您确定sort_headers()不是仅使用order by子句修改查询集吗?您可以将sort_headers()发布到您的问题吗?