Misleading Code in Admin Example
Reported by: |
wkschwartz@… |
Owned by: |
Baptiste Mispelon <bmispelon@…> |
Component:
|
Documentation
|
Version:
|
1.7-rc-2
|
Severity:
|
Normal
|
Keywords:
|
|
Cc:
|
|
Triage Stage:
|
Accepted
|
Has patch:
|
yes
|
Needs documentation:
|
no
|
Needs tests:
|
no
|
Patch needs improvement:
|
no
|
Easy pickings:
|
yes
|
UI/UX:
|
no
|
In https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_search_results there is a code example:
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
queryset |= self.model.objects.filter(age=search_term_as_int)
except:
pass
return queryset, use_distinct
This code catches a SystemExit
when all it meant to do was deal with the case when search_term
is not an integer. See https://docs.python.org/2/howto/doanddont.html#except
Better would be:
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
except ValueError:
pass
queryset |= self.model.objects.filter(age=search_term_as_int)
return queryset, use_distinct
Change History
(8)
Triage Stage: |
Unreviewed → Accepted
|
Owner: |
changed from nobody to Gabriel Muñumel
|
Status: |
new → assigned
|
Owner: |
Gabriel Muñumel removed
|
Status: |
assigned → new
|
Owner: |
set to Baptiste Mispelon <bmispelon@…>
|
Resolution: |
→ fixed
|
Status: |
new → closed
|
Having the
queryset |= ...
line after the except clause, as in the suggested example, causes an exception in caseint(search_term)
fails.