Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I specify the output_field kwarg in this complex query?

Tags:

django

I wrote a little survey app. I have a query that causes an exception upon upgrade to Django 2.0:

Expression contains mixed types. You must set output_field.

Here's a few relationships necessary to understand the query (where --fk--> indicats a foreign key):

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

Here's my query:

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'))
    )

It's fine up until the last annotate, but I don't know where to add the output_field kwarg since I only have F and Count models. Count outputs an IntegerField by definition, F complains if I try to add that kwarg.

How do I fix this?

like image 525
Escher Avatar asked Oct 31 '25 20:10

Escher


1 Answers

Thanks to @Gahan's comment, I discovered I need to use an ExpressionWrapper to perform arithmetic on F objects within an annotation. Docs here.

The last part hence becomes:

.annotate(
    completion=ExpressionWrapper(
        100*Count('id')\
        (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')),
    output_field=FloatField()
)
like image 186
Escher Avatar answered Nov 03 '25 12:11

Escher