﻿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
37539	Model formsets can duplicate or omit objects from an annotated queryset	Cleisson	Cleisson	"Since Django 6.1, passing an annotated queryset to a model formset can change which objects appear in the formset. With one book and two reviews, the queryset returns the book with a count of two. The formset shows it twice with a count of one each. Filtering for books with at least two reviews leaves the formset empty.

Put these models in `library/models.py` in an installed app named `library`.

{{{#!python
from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=100)

    class Meta:
        ordering = [""reviews__rating""]


class Review(models.Model):
    book = models.ForeignKey(
        Book, related_name=""reviews"", on_delete=models.CASCADE
    )
    rating = models.IntegerField()
}}}

Run `python manage.py makemigrations library` and `python manage.py migrate`, then run this in `python manage.py shell` against empty tables.

{{{#!python
from django.db.models import Count
from django.forms import modelformset_factory
from library.models import Book, Review

book = Book.objects.create(title=""Example"")
Review.objects.create(book=book, rating=2)
Review.objects.create(book=book, rating=3)
books = Book.objects.annotate(n=Count(""reviews""))
BookFormSet = modelformset_factory(Book, fields=[""title""], extra=0)

def form_rows(queryset):
    forms = BookFormSet(queryset=queryset)
    return [(form.instance.title, form.instance.n) for form in forms]

print(""queryset:"", [(book.title, book.n) for book in books])
print(""formset:"", form_rows(books))
print(""formset with n >= 2:"", form_rows(books.filter(n__gte=2)))
}}}

On Django 6.0.10, all three lines contain `[('Example', 2)]`. On 6.1, 6.1.3, and `main` at `f0e7bd9088`, SQLite produces different rows for the formset.

{{{
queryset: [('Example', 2)]
formset: [('Example', 1), ('Example', 1)]
formset with n >= 2: []
}}}

This started with [https://github.com/django/django/commit/856c915326768962806705ca7733e4abbb8f794f 856c915326] (#37004). When adding a primary-key tiebreaker, `BaseModelFormSet.get_queryset()` reapplies `Meta.ordering` even though the ORM ignores it for grouped queries. Ordering by `reviews__rating` adds the rating to the SQL `GROUP BY` and splits the book into two groups. Passing `books.order_by(""pk"")` to the formset keeps the count at two.

#37531 fixed a crash with sliced querysets. This queryset is unsliced, and the example still fails on the commit that fixed #37531.

A patch with regression tests is on my fork. Both formset test modules pass with the fix on SQLite and PostgreSQL 18.6.

OpenAI Codex (GPT-6.2 Astra and Sol) helped investigate the regression, prepare the patch and tests and run the examples."	Bug	assigned	Forms	6.1	Release blocker				Unreviewed	0	0	0	0	0	0
