我有这个加入:
lawyers = Lawyer.objects.filter(last__iexact=last_name).filter(first__icontains=first_name)
如果您尝试姓氏:Abbas 和名字:Amr,它会告诉您 amr abbas 有 1 个同学。
但是,如果您仅尝试 First name,则表明数据库中没有名为 amr 的律师(显然有)。
如果我更改(last__iexact=last_name)
为,(last__icontains=last_name)
则将姓氏留空可以正常工作并找到 amr。
但是last__icontains=last_name
如果你搜索“collin”,你也会得到“collins”和“collingwood”,这不是我想要的。
你知道我可以如何使用iexact
它,如果它是空白的,也可以忽略它吗?
谢谢
这是视图函数:
def search_form(request):
if request.method == 'POST':
search_form = SearchForm(request.POST)
if search_form.is_valid():
last_name = search_form.cleaned_data['last_name']
first_name = search_form.cleaned_data['first_name']
lawyers = Lawyer.objects.filter(last__iexact=last_name).filter(first__icontains=first_name)
if len(lawyers)==0:
form = SearchForm()
return render_to_response('not_in_database.html', {'last': last_name, 'first': first_name, 'form': form})
if len(lawyers)>1:
form = SearchForm(initial={'last_name': last_name})
return render_to_response('more_than_1_match.html', {'lawyers': lawyers, 'last': last_name, 'first': first_name, 'form': form})
q_school = Lawyer.objects.filter(last__icontains=last_name).filter(first__icontains=first_name).values_list('school', flat=True)
q_year = Lawyer.objects.filter(last__icontains=last_name).filter(first__icontains=first_name).values_list('year_graduated', flat=True)
lawyers1 = Lawyer.objects.filter(school__iexact=q_school[0]).filter(year_graduated__icontains=q_year[0]).exclude(last__icontains=last_name)
form = SearchForm()
return render_to_response('search_results.html', {'lawyers': lawyers1, 'last': last_name, 'first': first_name, 'form': form})
else:
form = SearchForm()
return render_to_response('search_form.html', {'form': form, })