Django:获取AVG的查询集不起作用

时间:2019-09-18 10:17:30

标签: python django

目前,我尝试获取我特定问题的所有答案的平均值 数据库。为此,我编写了以下查询集。答案都是数字的, 但我的查询集似乎仍然有问题。我收到以下错误消息 function avg(text) does not exist LINE 1: SELECT AVG("surveys_answer"."answer") AS "avg" FROM "surveys...

answers = Question.objects.filter(
    focus=QuestionFocus.AGE,
    survey__event=self.request.event,
    survey__template=settings.SURVEY_POST_EVENT,
).aggregate(avg=Avg('answers__answer'))

models.py

class Question(TimeStampedModel):
    survey = models.ForeignKey([...])
    question_set = models.ForeignKey([...])
    title = models.CharField([...])
    help_text = models.TextField([...])
    type = models.CharField([...])
    focus = models.CharField([...])
    required = models.BooleanField([...])
    position = models.PositiveSmallIntegerField([...])

class Answer(TimeStampedModel):
    question = models.ForeignKey(related_name='answers')
    response = models.ForeignKey([...])
    answer = models.TextField([...])
    choices = models.ManyToManyField([...])

1 个答案:

答案 0 :(得分:0)

  

答案都是数字,但是我的查询集似乎仍然有问题。

这与您的查询集无关。那是您的模型和数据库的问题。如果您的数值是数字,则需要使用IntegerFieldDecimalFieldFloatField或其他将数值存储在数据库中的数据。例如:

class Answer(TimeStampedModel):
    question = models.ForeignKey(related_name='answers')
    response = models.ForeignKey([...])
    answer = models.IntegerField([...])
    choices = models.ManyToManyField([...])

严格来说,您可以将其转换为数据库中的数字数据,但这是非常不安全的,只会让建模问题持续存在:

from django.db.models import IntegerField
from django.db.models.functions import Cast

answers = Question.objects.filter(
    focus=QuestionFocus.AGE,
    survey__event=self.request.event,
    survey__template=settings.SURVEY_POST_EVENT,
).aggregate(avg=Avg(Cast('answers__answer', output_field=IntegerField())))

但是,与试图通过查询减轻问题相比,防止在数据库中输入非数字数据要好得多。