简体   繁体   English

Django +在数据库上搜索

[英]django + search on database

I want to enable the user to search for other users across multiple columns in the user model. 我想使用户能够跨user模型中的多个列搜索其他用户。 Namely the first_name , last_name , and email fields. first_namelast_nameemail字段。 I'm doing MySQL full text search for now but I'm not convinced that's the right way for me to proceed. 我现在正在进行MySQL全文搜索,但我不认为这是进行下一步的正确方法。 Does anybody know how MySQL full text searching stacks up against Solr and other third party providers? 有人知道MySQL全文搜索如何与Solr和其他第三方提供商竞争吗?

I'm looking at searchify and websolr as potentials. 我正在将searchify和websolr视为潜力。 But for 1 table to do full text searching across 3 columns, would it be worth it? 但是,对于一张表进行3列全文搜索,是否值得?

Searching against the database itself is rather slow. 针对数据库本身的搜索相当慢。 The recommended approach is using a search engine, like Solr, Whoosh, etc to generate the indexes. 推荐的方法是使用搜索引擎(如Solr,Whoosh等)生成索引。 Haystack is a very useful django app that let's you abstract the search engines and have templates to use when indexing. Haystack是一个非常有用的django应用程序,可让您抽象化搜索引擎并提供建立索引时要使用的模板。

So with the template you can have a template like: 因此,使用该模板,您可以拥有一个类似于以下内容的模板:

{{user.first_name}}
{{user. last_name}}
{{user.email}}

And it will generate the search results you're looking for. 它将生成您要查找的搜索结果。

This is how I do it 这就是我的方法

#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):
    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 

def get_query(query_string, search_fields):
    query = None
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None
        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

And the view: 和视图:

# views.py
from django.shortcuts import render_to_response
from django.contrib.auth.models import User

def search(request):
    query = request.GET.get('q', '')
    if query:
        entry_query = get_query(query, ['first_name', 'last_name', 'email'])
        users = User.objects.filter(entry_query).order_by('-pub_date')
    else:
        entries_list = []
    return render_response(request, 'blog/list.html', {'entries': entries_list})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM