Django搜索表单也希望能够进行部分搜索

时间:2011-01-14 15:27:55

标签: django forms search views models

我搜索了查找特定项目的alternate_id。如果存在没有空格的逗号,则此搜索可以允许替换if是否进行多次搜索。但我希望我的搜索表单能够进行“部分搜索”。所以搜索*,2ndid将给出所有结果......,2ndid

Alternate id是一个字符串。不是整数。我作为__in的唯一原因是因为我可以执行多次搜索。

def search_item(request, client_id = 0):
    client = None
    if client_id != 0:
        try:
            client = models.Client.objects.get(pk = client_id)
        except:
            pass

        items = None
        Q_alt_ids = Q()
        if request.method == 'POST':
             form = forms.SearchItemForm(request.POST)
             if form.is_valid():
             alternate_id = form.cleaned_data['alternate_id']
             items = client.storageitem_set.all()
       if alternate_id:
                alternate_ids= alternate_id.lower().split(",")
                Q_alt_ids = Q(alternative_id__in = alternate_ids)
        return render_to_response('items.html', {'items':items, 'client':client}, context_instance = RequestContext(request))
 else:
        HttpResponse(client)
        if client is not None:
            form = forms.SearchItemForm(initial = {'client':client.pk})
        else:
            form = forms.SearchItemForm()
    return render_to_response('search_items.html', {'form':form}, context_instance = RequestContext(request))

2 个答案:

答案 0 :(得分:1)

除了编写自己的SQL之外,我认为唯一可以处理像通配符这样的健壮查询的开箱即用解决方案是一个正则表达式。如果通配符始终位于相同位置(例如后跟部分字符串),则可以使用field__startswith=partial查找类型。

但一般来说,通配符=正则表达式

http://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex

,但 我怀疑您可能正在寻找containsicontains过滤器查找类型。

如果你想在'hello world'中匹配'hello','ello','world':

# first split the string by comma
queries = form.cleaned_data.get('query', '').split(',')

# populate queries list
query_list = [Q(**{'alternative_id__icontains' : query }) for query in queries]

# join queries list with the OR operator
results = MyModel.objects.filter(  reduce(operator.or_, query_list)  )

答案 1 :(得分:-1)

感谢yuji的回答。需要这些改变才能使其发挥作用。

 return_all = False
    filters = []
                 if alternate_id:
                    alternate_ids = alternate_id.lower().split(",") 
                    for item in alternate_ids:
                    if '*' not in item:
                        filters.append( Q(alternative_id=item) )
                    elif item == '*':
                        return_all = True
                    elif item.startswith('*') and item.endswith('*'):
                        filters.append( Q(alternative_id__icontains=item.strip('*')) )
                    elif item.startswith('*'):
                        filters.append( Q(alternative_id__endswith=item.strip('*')) )
                    elif item.endswith('*'):
                        filters.append( Q(alternative_id__startswith=item.strip('*')) )
                    else:
                        assert False, "Wildcard in invalid position (valid is.. *XX, *XX*, XX*)"

if not filters or return_all:
    items = items.all()
else:
    items = items.filter(reduce(operator.or_, filters))