Probeer dit:
Question.objects.annotate(
answer_amount=Count('answers'),
is_user_agreed=F('answers__is_agreed'),
).order_by('id', '-answers__is_agreed').distinct('id')
Als question
heeft geen answers
, dan question.is_user_agreed
is None
. Als question
heeft ten minste één answer
met answer.is_agreed=True
, dan question.is_agreed
is True
. Anders is_user_agreed
is False
.
Of dit:
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 een lijst van id
van questions
, die ten minste één answer
. hebben met answer.is_agreed=True
.