在这个复杂的查询中,我应该在哪里指定output_field kwarg?

在这个复杂的查询中,我应该在哪里指定output_field kwarg?

问题描述:

我写了一个小调查应用程序。我有一个查询在升级到Django 2.0时导致异常:在这个复杂的查询中,我应该在哪里指定output_field kwarg?

表达式包含混合类型。您必须设置output_field。

这里有必要几个关系理解查询(其中--fk--> indicats外键):

response --fk--> question --fk--> survey 
response --fk--> person 

这里是我的查询:

answered_surveys = SurveyResponse.objects.all()\ 
    .values('fk_question__fk_survey__hash', 'fk_question__fk_survey__name')\ 
    .annotate(
     nb_respondants = Count('fk_person', distinct=True), 
     survey_name = F('fk_question__fk_survey__name'), 
     survey_hash = F('fk_question__fk_survey__hash') 
    )\ 
    .annotate(
     completion=100*Count('id')/ 
     (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')) 
    ) 

它的罚款,直到最后annotate,但我不知道在哪里添加output_field克瓦格,因为我只有FCount模型。根据定义,Count输出一个IntegerField,如果我尝试添加kwarg,F会抱怨。

我该如何解决这个问题?

+1

此[链接](https://code.djangoproject.com/ticket/24485)可以帮助你 – Gahan

+0

谢谢,这正是它是什么。很酷,看到该功能背后的历史背景。 – Escher

感谢@ Gahan的评论,我发现我需要使用ExpressionWrapper对注释中的F对象执行算术运算。 Docs here。因此

最后一部分就变成了:

.annotate(
    completion=ExpressionWrapper(
     100*Count('id')\ 
     (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')), 
    output_field=FloatField() 
)