[Django]-Django: NotImplementedError: annotate() + distinct(fields) is not implemented

15👍

✅

Try this:

Question.objects.annotate(
    answer_amount=Count('answers'),
    is_user_agreed=F('answers__is_agreed'),
).order_by('id', '-answers__is_agreed').distinct('id')

If question has no answers, then question.is_user_agreed is None. If question has at least one answer with answer.is_agreed=True, then question.is_agreed is True. Otherwise, is_user_agreed is False.

Or this:

agreed_questons = Answer.objects.filter(
    is_agreed=True,
).values_list('question_id', flat=True).distinct()

Question.objects.annotate(
    answer_amount=Count('answers'),
    is_agreed=Case(
        When(id__in=agreed_questions, then=True),
        When(answers__isnull=True, then=None),
        default=False,
        output_field=NullBooleanField(),
    ),
)

agreed_questons is list of id of questions, that have at least one answer with answer.is_agreed=True.

Leave a comment