fix(queryset): make distinct().count() ignore join-duplicated rows#2255
Open
Sanjays2402 wants to merge 1 commit into
Open
fix(queryset): make distinct().count() ignore join-duplicated rows#2255Sanjays2402 wants to merge 1 commit into
Sanjays2402 wants to merge 1 commit into
Conversation
QuerySet.count() always emitted COUNT(*), which counts every row the query produces. When the queryset is distinct() and the filter spans a m2m (or any other row-multiplying join), the returned objects are de-duplicated by the SELECT DISTINCT but the count was not, so count() reported more rows than the queryset actually yields. CountQuery now receives the _distinct flag and counts distinct primary keys instead. Grouped queries keep the existing windowed COUNT(*). Closes tortoise#2178
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #2178
Description
QuerySet.count()always emittedCOUNT(*), which counts every row the query produces.distinct()only setsSELECT DISTINCTon the row query, so when a filter spans an m2m (or any other row-multiplying join) the returned objects were de-duplicated but the count was not.CountQuerynow receives the_distinctflag and counts distinct primary keys; grouped queries keep the existing windowedCOUNT(*).Motivation and Context
Fixes #2178:
Model.filter(m2m_field__name__in=[...]).distinct()returns 1 object but.count()returned 3.How Has This Been Tested?
Added
test_distinct_count_with_m2m_joinintests/test_queryset.py. It fails ondevelop(assert 3 == 1) and passes with the fix. Full suite run on SQLite is unchanged otherwise (1789 -> 1790 passed, same 3 pre-existing environment failures before and after).Checklist: