2017-12-18 98 views
0

我寫了一個小調查應用程序。我有一個查詢在升級到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

回答

0

感謝@ 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() 
)