Opened 11 minutes ago
#37531 assigned Bug
Model formsets raise TypeError with sliced querysets ordered by a non-unique field
| Reported by: | Cleisson | Owned by: | Cleisson |
|---|---|---|---|
| Component: | Forms | Version: | 6.1 |
| Severity: | Release blocker | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
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:
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 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.