﻿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
34449	ProgrammingError: non-integer constant in GROUP BY with Case When and annotate Count	Guillaume LEBRETON	nobody	"I had a suprising error, that appears so far only with postgres. Lets have this models and tests:

{{{
# models.py
class Person(models.Model):
    name = models.CharField(max_length=10, blank=True, null=True)


class QuantitativeAttribute(models.Model):
    value = models.PositiveIntegerField()
    name = models.CharField(max_length=10)
    person = models.ForeignKey(Person,  on_delete=models.CASCADE)


# tests.py
class QuantitativeTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.p1 = Person.objects.create(name='p1')

        QuantitativeAttribute.objects.create(
            person=cls.p1,
            value=27,
            name='age',
        )

    def test_annotate_fail(self):
        """"""This test is successfull with sqlite""""""
        expected_qs = [{'alarm': 'warning', 'number': 1, 'pk': 1}]

        qs = Person.objects\
            .all()\
            .annotate(number=Count('quantitativeattribute'))

        qs = qs.annotate(alarm=Case(
            When(id__in=[], then=Value('danger', output_field=models.CharField())),
            default=Value('warning')

        ))

        self.assertQuerysetEqual(qs.values('pk', 'number', 'alarm'), expected_qs)
        # => raises django.db.utils.ProgrammingError: non-integer constant in GROUP BY
        # LINE 1: ...ibute"".""person_id"") GROUP BY ""argent_person"".""id"", 'warning'

    def test_annotate_success(self):
        """"""This test is successfull with sqlite and postgres""""""
        expected_qs = [{'alarm': 'warning', 'number': 1, 'pk': 1}]

        qs = Person.objects\
            .all()\
            .annotate(number=Count('quantitativeattribute'))

        qs = qs.annotate(alarm=Case(
            # When(id__in=[], then=Value('danger', output_field=models.CharField())),
            default=Value('warning')

        ))

        self.assertQuerysetEqual(qs.values('pk', 'number', 'alarm'), expected_qs)

}}}

It appear that in the case of the first test, django adds an unwanted groupby argument when database is postgresql(v15), but everithing is ok with sqlite.
Note that is did search for a similar issues but none seemed to be the exact same problem."	Bug	closed	Database layer (models, ORM)	4.1	Normal	fixed			Unreviewed	0	0	0	0	0	0
