Opened 3 months ago

Closed 2 months ago

#35690 closed Cleanup/optimization (fixed)

Calling queryset.in_bulk() after queryset.values() or queryset.values_list() results in unhelpful error

Reported by: john-parton Owned by: john-parton
Component: Database layer (models, ORM) Version: 5.1
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Calling

MyModel.objects.values().in_bulk()

Results in a rather annoying error message that doesn't help the user.

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/john/Code/ecom/.venv/lib/python3.12/site-packages/django/db/models/query.py", line 1156, in in_bulk
    return {getattr(obj, field_name): obj for obj in qs}
            ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'pk'

This is because the in_bulk method assumes that the queryset has the default _iterable_class (ModelIterable) and is attempting to access a property on an object, but the _iterable_class returns dictionaries.

The correct behavior should be either to:

  1. Raise a more helpful error if the user attempts to call in_bulk() where the _iterable_class isn't the standard ModelIterable; or
  2. Define behavior for when in_bulk() is called in that case. (I think that might be rather challenging, so Behavior 1 is probably the better option.)

Change History (6)

comment:2 by john-parton, 3 months ago

Has patch: set

comment:3 by john-parton, 3 months ago

I've created a second more complicated pull request that implements some reasonable behavior: https://github.com/django/django/pull/18497

comment:4 by Sarah Boyce, 3 months ago

Owner: set to john-parton
Status: newassigned
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

Raising a more helpful error sounds good to me

comment:5 by Sarah Boyce, 2 months ago

Triage Stage: AcceptedReady for checkin

Note that this has similarities to #26565
PR

comment:6 by Sarah Boyce <42296566+sarahboyce@…>, 2 months ago

Resolution: fixed
Status: assignedclosed

In e4a2e22:

Fixed #35690 -- Errored nicely when using in_bulk() with a values() or values_list() queryset.

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