Zkuste toto:
Question.objects.annotate(
answer_amount=Count('answers'),
is_user_agreed=F('answers__is_agreed'),
).order_by('id', '-answers__is_agreed').distinct('id')
Pokud question
nemá žádné answers
a poté question.is_user_agreed
je None
. Pokud question
má alespoň jednu answer
s answer.is_agreed=True
a poté question.is_agreed
je True
. V opačném případě is_user_agreed
je False
.
Nebo toto:
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
je seznam id
z questions
, které mají alespoň jednu answer
s answer.is_agreed=True
.