[Django]-Queryset is evaluated when sliced?

6đź‘Ť

âś…

The full paragraph explains when slicing will evaluate the queryset, and when not (emphasis mine):

  • Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python’s array-slicing syntax. Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated also returns a list.

Django will only evaluate the queryset when you use the step parameter, for example queryset[::2], since this can’t be translated into an SQL query. In other cases, slicing an unevaluated queryset will return another unevaluated queryset, and Django will add a LIMIT and/or OFFSET to the query.

👤knbk

Leave a comment