Opened 7 years ago

Closed 7 years ago

#29135 closed Cleanup/optimization (fixed)

get_object_or_404() and get_list_or_404() swallow AttributeError in queryset filtering

Reported by: David Hagen Owned by: Yuri Shikanov
Component: Core (Other) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Here is the code for get_list_or_404:

def get_list_or_404(klass, *args, **kwargs):
    queryset = _get_queryset(klass)
    try:
        obj_list = list(queryset.filter(*args, **kwargs))
    except AttributeError:
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_list_or_404() must be a Model, Manager, or "
            "QuerySet, not '%s'." % klass__name
        )
    if not obj_list:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    return obj_list

The try-catch block is far too broad. Any AttributeError raised during the call to filter is swallowed and converted into an incorrect and confusing error message. This should be changed to either if not hasattr(queryset, 'filter'): raise ... or try: method = queryset.filter; except AttributeError: .... The same thing happens with queryset.get(*args, **kwargs) in get_object_or_404'.

Change History (7)

comment:1 by Tim Graham, 7 years ago

Component: UncategorizedCore (Other)
Summary: `get_object_or_404` and `get_list_or_404` swallows exceptionsget_object_or_404() and get_list_or_404() swallow AttributeError in queryset filtering
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

comment:2 by Yuri Shikanov, 7 years ago

Owner: changed from nobody to Yuri Shikanov
Status: newassigned

comment:3 by Yuri Shikanov, 7 years ago

I've opened PR

comment:4 by Yuri Shikanov, 7 years ago

Has patch: set

comment:5 by Carlton Gibson, 7 years ago

Patch needs improvement: set

Just minor edits on patch needed. (Comments on PR.)

comment:6 by Carlton Gibson, 7 years ago

Patch needs improvement: unset
Triage Stage: AcceptedReady for checkin

comment:7 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: assignedclosed

In eb002e78:

Fixed #29135 -- Prevented get_object/list_or_404() from hiding AttributeError raised by QuerySet filtering.

Note: See TracTickets for help on using tickets.
Back to Top