Opened 12 minutes ago

Last modified 9 minutes ago

#37539 assigned Bug

Model formsets can duplicate or omit objects from an annotated queryset

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

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.

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.

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 ​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.

Change History (1)

comment:1 by Cleisson, 9 minutes ago

Here’s the patch mentioned in the report: ​​https://github.com/cleissonom/django/pull/4

Note: See TracTickets for help on using tickets.
Back to Top