通过一个django表单字段搜索多个单词



嘿!

我有一个结果表,在其中我可以通过django表单过滤条目。例如:国家:"瑞典">

我会得到所有"瑞典"是"国家"栏中的值的条目。

我希望如果我输入"瑞典,德国",我会得到数据库中国家是"瑞典"或"德国"的所有结果。布尔输入("Weden OR/AND Germany")也很棒!

这是我目前的看法:

#views.py
def search_institution(request):
if request.method == "POST":
form = SearchInstitutionsForm(request.POST)
if form.is_valid():
query_set = Institution.objects.filter(
name__contains=form.cleaned_data['name']
)
context = {
"result_data": list(query_set.values()),
'form': form
}
return render(request, "search_form.html", context)
else:
form = SearchInstitutionsForm()
context = {
"result_data": list(Institution.objects.values()),
"form": form
}
return render(request, "search_form.html", context)

我试过了:

query_set = Institution.objects.filter(name__contains=x) for x in ['name']))
#and
query_set = Institution.objects.filter(reduce(operator.and_, (Q(name__contains=x) for x in ['name'])) 

只得到一个空的结果表。

query_set = Institution.objects.filter(
name__search=form.cleaned_data['name']
)

在这里我得到了错误:>不允许在字段上查找不支持的CharField或联接。

然后我在安装的应用程序中的设置中放入django.contrib.postgres.search,现在发现错误>无法识别的令牌:"@">

我的表单和模板:

#forms.py
class SearchInstitutionsForm(forms.Form):
name = forms.CharField(label='Name', required=False)
#search_form.html
<form method="post">
{{ form.as_table }}
{% csrf_token %}
<input type="submit" value="Search">
</form>

有什么办法解决我的问题吗?谢谢你的帮助!:)

在这里,您可以使用Q函数。首先,拆分两个关键字。

split = form.cleaned_data['name'].split(' ')
lookup = Q(name__contains=split[0]) | Q(name__contains=split[1])
query_set = Institution.objects.filter(
lookup
)

使用上面的代码更改查询集。

这是我能写的最接近的,它应该能解决你的问题。我仍然有一个要点,那就是这可以用更好的方式来完成。

我们想要得到所有那些包含任何一个用逗号分隔的名称的行。所以我们希望有OR条件。

from django.db.models import Q
def get_lookup_query(names_str):
# Assuring names_str is not empty string i.e ""
# Also it cannot contain white space only i.e "   "
assert len(names_str.strip()) > 0, "names_str can neither be empty string nor contain white spaces only"
# Splitting names based on comma and stripping white spaces 
# from front and back for each name.
names_list = [n.strip() for n in names_str.split(',')]
# It would be good to have case insensitive match
lookup_query = Q(name__icontains = names_list[0])
len_names_list = len(names_list)
if len_names_list > 1:
for i in range(1,len_names_list):
lookup_query |= Q(name__icontains = names_list[i])
return lookup_query

现在您可以使用这个获取查询集

names_str = form.cleaned_data['name']
lookup_query = get_lookup_query(names_str)
query_set = Institution.objects.filter(lookup_query)

感谢您的帮助和想法!

我解决了在SearchInstitutionForm()中编写一个新函数来分割forms.py中的字符串的问题。

def clean_name(self):
name_str = self.cleaned_data["name"]
if not name_str:
return []
name_list = [string.strip() for string in name_str.split(",")]
return name_list

并添加了一个单独的查询函数,以使代码在我的views.py中更干净、更简单。我的视图和查询变得相当复杂:D

我现在可以为所有必要的部分添加类似的功能。

最新更新