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

问题描述 投票:2回答:1

我写了一个小调查应用程序。我有一个查询,在升级到Django 2.0时导致异常:

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

这里有一些理解查询所需的关系(--fk-->指示外键):

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 kwarg,因为我只有FCount模型。 Count根据定义输出一个IntegerField,如果我尝试添加那个kwarg,F会抱怨。

我该如何解决?

django
1个回答
3
投票

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

最后一部分因此变成:

.annotate(
    completion=ExpressionWrapper(
        100*Count('id')\
        (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')),
    output_field=FloatField()
)
© www.soinside.com 2019 - 2024. All rights reserved.