#36426: prefetch_related_objects() is doc'd to accept iterables but only accepts
sequences
-------------------------------------+-------------------------------------
Reporter: Jacob Walls | Type: Bug
Status: new | Component: Database
| layer (models, ORM)
Version: 5.2 | Severity: Normal
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
-------------------------------------+-------------------------------------
The docs say `prefetch_related_objects()`
[
https://docs.djangoproject.com/en/5.2/ref/models/querysets/#django.db.models.prefetch_related_objects
accepts iterables], but it only accepts sequences.
{{{#!py
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 [
https://github.com/typeddjango/django-
stubs/blob/5bb841674610e88a162475b7ecf2e950a92c23a8/django-
stubs/db/models/query.pyi#L247 types] the argument as `Model[Iterable]`.
--
Ticket URL: <
https://code.djangoproject.com/ticket/36426>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.