﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35665	"Prefetch() fails with ""OrderByList"" when queryset has no order_by and is sliced"	Andrew	Simon Charette	"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']
}}}


"	Bug	closed	Database layer (models, ORM)	5.1	Release blocker	fixed	prefetch slice order_by		Ready for checkin	1	0	0	0	0	0
