#35665: Prefetch() fails with "OrderByList" when queryset has no order_by and is
sliced
-------------------------------------+-------------------------------------
Reporter: Andrew | Type: Bug
Status: new | Component: Database
| layer (models, ORM)
Version: 5.1 | Severity: Normal
Keywords: prefetch slice | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
In {{{v5.1}}} the Prefetch operator causes an issue when no
{{{order_by()}}} is specified, and the query contains a slice.
* Must have no order by (either explict {{{order_by()}}} or model Meta
contains no order by)
* Must be sliced - any form works, {{{:10}}}, {{{10:}}}, {{{10:20}}}
Does not crash in {{{v5.0.7}}}. I did not see this mentioned in the
{{{Prefetch}}} documentation, or the changelog.
{{{
short_list = Prefetch(
"products",
queryset=Product.objects.order_by()[:10],
to_attr="short_list",
)
query = Store.objects.prefetch_related(short_list)
print(query) # errors
}}}
**The stack trace:**
{{{
File "python3.12/site-packages/django/db/models/expressions.py", line
1896, in __init__
self.order_by = OrderByList(*self.order_by)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "python3.12/site-packages/django/db/models/expressions.py", line
1414, in __init__
super().__init__(*expressions, **extra)
File "python3.12/site-packages/django/db/models/expressions.py", line
1382, in __init__
raise ValueError(
ValueError: OrderByList requires at least one expression.
}}}
I was able to replicate this in a clean project, against sqlite, with the
following 2 simple models, used in the example above:
{{{
class Store(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
store = models.ForeignKey(Store, on_delete=models.CASCADE,
related_name='products')
name = models.CharField(max_length=100)
class Meta:
ordering = ['name']
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/35665>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/0107019135e3bbed-85c5e5ac-8e8f-42a2-b13c-96e4c2dbc10e-000000%40eu-central-1.amazonses.com.