Django搜索表单歧义页跳转异常求助:视图代码无法正常工作
Fixing Django Search Disambiguation Redirect Issue
Hey there! I see the problem with your search view logic—let's break it down and fix it so your disambiguation page redirect works correctly.
What's Wrong with the Current Code?
Your main issue is the line if sr is sd:—here's why it doesn't work:
- The
isoperator checks if two variables point to the exact same object in memory, not whether both QuerySets contain results or have overlapping matches. - Even if both
srandsdhave results, they'll always be different QuerySet objects, so this condition will never be true.
Corrected View Code
Here's the updated searchesView with the proper logic to trigger the disambiguation page when both band and album matches exist:
class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: # Get matches for band and disco fields band_matches = Info.objects.filter(band__icontains=srch) disco_matches = Info.objects.filter(disco__icontains=srch) # Check if both have matching results if band_matches.exists() and disco_matches.exists(): return render(self.request, 'search/disambigua.html') # If only band matches exist elif band_matches.exists(): paginator = Paginator(band_matches, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( self.request, 'search/searches.html', {'sr': band_matches, 'page_obj': page_obj} ) # If only disco matches exist (optional: handle this case too) elif disco_matches.exists(): paginator = Paginator(disco_matches, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( self.request, 'search/searches.html', {'sd': disco_matches, 'page_obj': page_obj} ) # No matches at all else: return render(self.request, 'search/searches.html') else: return render(self.request, 'search/searches.html')
Key Changes Explained
- Replaced
sr is sdwithband_matches.exists() and disco_matches.exists(): This checks if both queries return at least one result, which is exactly your disambiguation trigger condition. - Renamed variables to
band_matchesanddisco_matchesfor clearer readability. - Added handling for cases where only one of the fields has matches (so users don't see empty results if only albums match).
- Removed unnecessary
Q()objects since you're only filtering on a single field each time.
Bonus Tip
If you ever need to check if the search term matches the same record in both fields (instead of any records in either), you'd adjust the condition to:
# Check if there's at least one record that matches both fields if Info.objects.filter(band__icontains=srch, disco__icontains=srch).exists(): return render(self.request, 'search/disambigua.html')
But based on your description, the first approach (any matches in both fields) is what you need.
内容的提问来源于stack exchange,提问作者user13128719
相关产品推荐
相关产品推荐

