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

前端 未结 1 1109
耶瑟儿~
耶瑟儿~ 2021-01-01 18:25

There are 2 simple models:

class Question(TimeStampedModel):
    text = models.CharField(max_length=40)

class Answer(TimeStampedModel):
    question = model         


        
相关标签:
1条回答
  • 2021-01-01 19:10

    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.

    0 讨论(0)
提交回复
热议问题