Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not store GROUP BY clauses for Subqueries #11092

Closed
wants to merge 1 commit into from

Conversation

PaulWay
Copy link
Contributor

@PaulWay PaulWay commented Mar 18, 2019

A Subquery in an annotation on a queryset can contains its own aggregate functions (e.g. COUNT) on the subquery's fields. However, these subqueries do not need to be included as GROUP BY clauses in the original query.

@charettes
Copy link
Member

Hello @PaulWay, I'm not sure if this is meant to address #30158 but as discovered in #11030 (comment) subquery annotations cannot always be removed from the group by clause.

For example, if a subquery annotation is explicitly included in a values() before an aggregate annotation the query must be grouped by it.

e.g.

def test_group_by_subquery_annotation(self):
    long_books_count_qs = Book.objects.filter(
            publisher=OuterRef('pk'),
            pages__gt=400,
        ).values(
            'publisher'
        ).annotate(count=Count('pk')).values('count')
    long_books_count_breakdown = Publisher.objects.annotate(
        long_books_count=Subquery(long_books_count_qs, IntegerField())
    ).values_list('long_books_count').annotate(
        total=Count('*'),
    )
    self.assertEqual(dict(long_books_count_breakdown), {
        None: 1,
        1: 4,
    })

@charettes
Copy link
Member

Hey @PaulWay, after a bit more investigation I figured out that is a duplicate of an issue that is fixed in the upcoming Django 2.2 release (rc1 should be released this week) so I'm going to close this PR. Thanks for giving it a try!

@charettes charettes closed this Mar 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants