Opened 4 months ago
Last modified 10 days ago
#36426 closed Cleanup/optimization
prefetch_related_objects() is doc'd to accept iterables but only accepts sequences — at Version 1
Reported by: | Jacob Walls | Owned by: | |
---|---|---|---|
Component: | Database layer (models, ORM) | 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 (last modified by )
The docs say prefetch_related_objects()
accepts iterables, but it only accepts sequences.
In [1]: from django.db.models import prefetch_related_objects In [2]: objs = set(Graph.objects.all()) In [3]: prefetch_related_objects(objs, "node_set") --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 1 ----> 1 prefetch_related_objects(objs, "node_set") File ~/py313/lib/python3.13/site-packages/django/db/models/query.py:2361, in prefetch_related_objects(model_instances, *related_lookups) 2355 break 2357 # Descend down tree 2358 2359 # We assume that objects retrieved are homogeneous (which is the premise 2360 # of prefetch_related), so what applies to first object applies to all. -> 2361 first_obj = obj_list[0] 2362 to_attr = lookup.get_current_to_attr(level)[0] 2363 prefetcher, descriptor, attr_found, is_fetched = get_prefetcher( 2364 first_obj, through_attr, to_attr 2365 ) TypeError: 'set' object is not subscriptable
We could adjust the docs, but at a glance we could probably instead adjust the implementation to just next()
instead of [0]
and accept iterables as documented.
django-stubs types the argument as Iterable[_Model]
.
Note:
See TracTickets
for help on using tickets.