﻿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
37531	Model formsets raise TypeError with sliced querysets ordered by a non-unique field	Cleisson	Cleisson	"Model formsets raise `TypeError: Cannot reorder a query once a slice has been taken.` when given a sliced queryset ordered by a non-unique field.

This worked in Django 6.0.10, but fails in 6.1, 6.1.3, and on main at `c67d872765`.

To reproduce, use an `Author` model with a non-unique `name` field and run the following against an empty table:

{{{
#!python
from django.forms import modelformset_factory
for name in [""Walt"", ""Charles"", ""Arthur"", ""Paul""]:
    Author.objects.create(name=name)
AuthorFormSet = modelformset_factory(Author, fields=[""name""], extra=0)
formset = AuthorFormSet(queryset=Author.objects.order_by(""name"")[1:3])
[form.instance.name for form in formset.forms]
}}}

Expected result: `[""Charles"", ""Paul""]`, preserving the order of the supplied queryset.

Actual result: `TypeError: Cannot reorder a query once a slice has been taken.`

I traced the regression to [https://github.com/django/django/commit/856c915326768962806705ca7733e4abbb8f794f 856c915326], introduced for #37004. The change makes `BaseModelFormSet.get_queryset()` append `pk` when the queryset isn’t totally ordered. For sliced querysets, this triggers an `order_by()` call after the slice, which Django doesn’t allow.

I confirmed this with a SQLite regression test that passes on the parent of that commit and fails on the commit itself.

I’ve also prepared a patch on my fork.

The regression test fails on main at `c67d872765` and passes with the patch on both SQLite and PostgreSQL 18.6. Both model formset test modules also pass on PostgreSQL.

If the ticket is accepted, I’ll open a pull request with the fix.

I used OpenAI Codex with GPT-6.2 Astra and GPT-6.2 Sol to investigate and reproduce the regression, prepare the patch, and run the tests."	Bug	assigned	Forms	6.1	Release blocker				Unreviewed	0	0	0	0	0	0
