Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions tests/test_queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ def test_slicing_negative_values(db):
_ = IntFields.all()[:-1]


def test_integer_indexing_not_supported(db):
with pytest.raises(
ParamsError,
match=(
r"QuerySet indices must be slices, not integers\. "
r"QuerySets are lazy and do not support random access\. "
r"Use await queryset\.first\(\), await queryset\.offset\(n\)\.first\(\), "
r"or await queryset\.all\(\) and index the returned list\."
),
):
# Use an index way outside reasonable bounds for the dataset, so we don't accidentally support it.
_ = IntFields.all()[1000]


def test_slicing_stop_before_start(db):
with pytest.raises(
ParamsError,
Expand Down
7 changes: 7 additions & 0 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,13 @@ def __getitem__(self, key: slice) -> QuerySet[MODEL]:
or None.
"""
if not isinstance(key, slice):
if isinstance(key, int):
raise ParamsError(
"QuerySet indices must be slices, not integers. "
"QuerySets are lazy and do not support random access. "
"Use await queryset.first(), await queryset.offset(n).first(), "
"or await queryset.all() and index the returned list."
)
raise ParamsError("QuerySet indices must be slices.")

if not (key.step is None or (isinstance(key.step, int) and key.step == 1)):
Expand Down
Loading