Home > Mobile >  Annotating without using Exists or SubQuery
Annotating without using Exists or SubQuery

Time:08-31

I have a client who is using Django 1.8. While they will be moved to the latest version, we need to run some queries before their migration, but obviously we can't use Exists or OuterRef.

In our case we want to annotate a queryset. eg

recordset = Question.objects.annotate( has_answers=Exists(Answers.objects.filter(question=OuterRef('pk'))) )

Is there a workaround to do the equivalent of the above annotation. What did people use in 'the olden days'?

CodePudding user response:

The following should work in 1.8, annotate each question with the count of answers and then use a conditional expression to convert that to a boolean

from django.db.models import Count, Case, When, BooleanField

Question.objects.annotate(
    num_answers=Count('answer')
).annotate(
    has_answers=Case(
        When(num_answers__gt=0, then=True),
        default=False,
        output_field=BooleanField()
    )
)

  • Related