Opened 3 years ago

Closed 3 years ago

#33298 closed Cleanup/optimization (fixed)

get_object_or_404()/get_list_or_404() don't document or test passing *args.

Reported by: Jaap Roes Owned by: Marcelo Galigniana
Component: Utilities 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

During code review I came across the following (slightly redacted) snippet:

doc = get_object_or_404(
    Document.objects.all(),
    Q(is_public=True) | Q(owner=request.user.id),
    id=data['document_id']
)

This looked odd to me, but the accompanying tests prove that it works. I wanted to comment that the first argument could just be Document but just to make sure I headed to the Django documentation of get_object_or_404.

To my surprise the usage of *args is not documented. While the function signature is shown as (klass, *args, **kwargs), only the klass and **kwargs arguments are documented and explained (same goes for get_list_or_404).

I then dug a bit deeper and looked at the tests. There I can only see tests that exercise the klass and **kwargs arguments, there are no tests that pass in *args or a combination *args and **kwargs.

This made me look at the actual implementation. There the docstring state:

klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.

I then dug deeper, and found that in the end the initial code snippet is converted to something like Document.objects.all().filter(Q(Q(is_public=True) | Q(owner=request.user.id), id=data['document_id'])).get().

So, in conclusion, is passing *args to get_object_or_404 and get_list_or_404 an expected use-case that should be tested/documented?

Change History (6)

comment:1 by Mariusz Felisiak, 3 years ago

Summary: get_object_or_404 / get_list_or_404 don't document/test *argsget_object_or_404()/get_list_or_404() don't document or test passing *args.
Triage Stage: UnreviewedAccepted

Thanks for the report! Agreed, we should document and add a small test for *args.

comment:2 by Marcelo Galigniana, 3 years ago

Owner: changed from nobody to Marcelo Galigniana
Status: newassigned

comment:3 by Marcelo Galigniana, 3 years ago

Has patch: set

I update the "Has patch" flag and link the PR to the ticket

https://github.com/django/django/pull/15112

comment:4 by Mariusz Felisiak, 3 years ago

Triage Stage: AcceptedReady for checkin

comment:5 by Jaap Roes, 3 years ago

Nice! Thanks Marcelo and Mariusz :-)

comment:6 by Mariusz Felisiak <felisiak.mariusz@…>, 3 years ago

Resolution: fixed
Status: assignedclosed

In 7f8f69f:

Fixed #33298 -- Added docs and tests for using Q objects with get_object_or_404()/get_list_or_404().

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