Opened 15 months ago
Closed 14 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:
- Raise a more helpful error if the user attempts to call
in_bulk()where the _iterable_class isn't the standard ModelIterable; or - 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:1 by , 15 months ago
comment:2 by , 15 months ago
| Has patch: | set |
|---|
comment:3 by , 15 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 , 15 months ago
| Owner: | set to |
|---|---|
| Status: | new → assigned |
| Triage Stage: | Unreviewed → Accepted |
| Type: | Bug → Cleanup/optimization |
Raising a more helpful error sounds good to me
comment:5 by , 14 months ago
| Triage Stage: | Accepted → Ready for checkin |
|---|
Pull request here https://github.com/django/django/pull/18496