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

发布于 2024-10-12 11:24:35 字数 1265 浏览 4 评论 0原文

我有一个搜索,寻找特定项目的alternate_id。如果存在不带空格的逗号,则此搜索可以允许替代 if 进行多次搜索。但我希望我的搜索表单也能够进行“部分搜索”。因此搜索 a*,2ndid 将给出所有结果 a......,2ndid

备用 id 是一个字符串。不是整数。我使用 as __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))

I have a search for that looks for an alternate_id for a particular item. This search for can allow alternative if to do multiple searches if there is a comma without spaces. But I want my search form to be able to do a "partial search" as well. So searching for a*,2ndid will give all results a......,2ndid

Alternate id is a string. Not an integer. The only reason why I have as __inwas because I could perform multiple searches.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回旧景 2024-10-19 11:24:35

除了编写自己的 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)  )

Aside from writing your own SQL, I think the only out of the box solution that can handle a robust query like a wildcard is a regular expression. If the wildcard is always in the same place, such as followed by a partial string, you could use the field__startswith=partial lookup type.

But in general, wildcards = regex

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

BUT,
I have a sneaking suspicion you might be looking for the contains or icontains filter lookup type.

If you want to match 'hello', 'ello', 'world' in 'hello 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)  )
绳情 2024-10-19 11:24:35

谢谢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))

thanks yuji for the answer. These change are needed to make it work.

 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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文