#25307: Cannot use .annotate with conditional expressions -------------------------------------+------------------------------------- Reporter: jproffitt | Owner: nobody Type: Bug | Status: new Component: Database layer | Version: master (models, ORM) | Severity: Normal | Resolution: Keywords: | Triage Stage: Accepted Has patch: 0 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 0 Easy pickings: 0 | UI/UX: 0 -------------------------------------+-------------------------------------
Comment (by jproffitt): That does make it break as well, but not simply just the use of distinct. If you use EITHER `.distinct()` OR `.annotate()` along with an `.aggregate()` that contains a conditional expression. (not sure exactly what part of the condition expression, but it must be either because of the `Case()` or the `When()`. I have made a completely useless example using the polls app in the django tutorial. I copied the polls models exactly, and created this query, which will cause the error to happen: {{{ counts = models.Choice.objects.annotate( used_count=Count('question') ).distinct().aggregate( yes=Sum(Case( When(choice_text='yes', then=F('votes')), default=0, output_field=IntegerField() )), no=Sum(Case( When(choice_text='no', then=F('votes')), default=0, output_field=IntegerField() )), ) }}} (Obviously, then `used_count` will always be 1, and its pretty pointless in this example, but you get the idea). So if you remove the either the `.annotate()` OR the `.distinct()`, the query still breaks the same way. The presence of either one causes it to break. But if you remove BOTH, the query runs fine. I do not know anything about the internals of the Query api, or I would help fix the problem. But it seems there is a problem when combining certain queryset methods like `annotate` or `distinct` with `aggregate`s that have condition expressions. I know it has to do with condition expressions, because doing the query like the following works just fine: {{{ counts = models.Choice.objects.annotate( used_count=Count('question') ).distinct().aggregate( yes=Sum('votes'), ) }}} -- Ticket URL: <https://code.djangoproject.com/ticket/25307#comment:12> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To post to this group, send email to django-updates@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/067.c89bfa9602d6adc92a20092cc68c71fd%40djangoproject.com. For more options, visit https://groups.google.com/d/optout.