开发者

How to make this django attribute name search better?

lcount = Open_Layers.objects.all()
form = SearchForm()

if request.method == 'POST': 
    form = SearchForm(request.POST) 
    if form.is_valid():
        data = form.cleaned_data
        val=form.cleaned_data['LayerName']

        a=Open_Layers()
        data = []
        for e in lcount:
            if e.Layer_name == val:     
                data = val 

        return render_to_response('searchresult.html', {'data':data})

    else:
        form = SearchForm()

 else:
    return render_to_response('mapsearch.html', {'form':form})

This just returns back if a particular "name" matches . How do to change it so that it returns when I give a search for "Park" , it should return Park1 , Park2 , Parking , Parkin i.e all开发者_运维知识库 the occurences of the park .


You can improve your searching logic by using a list to accumulate the results and the re module to match a larger set of words.

However, this is still pretty limited, error prone and hard to maintain or even harder to make evolve. Plus you'll never get as nice results as if you were using a search engine.

So instead of trying to manually reinvent the wheel, the car and the highway, you should spend some time setting up haystack. This is now the de facto standard to do search in Django.

Use woosh as a backend at first, it's going to be easier. If your search get slow, replace it with solr.

EDIT:

Simple clean alternative:

Open_Layers.objects.filter(name__icontains=val)

This will perform a SQL LIKE, adding %` for you.

This going to kill your database if used too often, but I guess this is probably not going to be an issue with your current project.

BTW, you probably want to rename Open_Layers to OpenLayers as this is the Python PEP8 naming convention.


Instead of

if e.Layer_name == val:     
   data = val 

use

if val in e.Layer_name:     
   data.append(e.Layer_name) 

(and you don't need the line data = form.cleaned_data)


I realise this is an old post, but anyway:

There's a fuzzy logic string comparison already in the python standard library.

import difflib 

Mainly have a look at:

difflib.SequenceMatcher(None, a='string1', b='string2', autojunk=True).ratio()

more info here: http://docs.python.org/library/difflib.html#sequencematcher-objects

What it does it returns a ratio of how close the two strings are, between zero and 1. So instead of testing if they're equal, you chose your similarity ratio.

Things to watch out for, you may want to convert both strings to lower case.

string1.lower()

Also note you may want to impliment your favourite method of splitting the string i.e. .split() or something using re so that a search for 'David' against 'David Brent' ranks higher.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜