简体   繁体   中英

Django: Query set to get AVG doesn't work

Currently, I try to get the average of all the answers to a specific question in my database. To achieve that I wrote the following query set. The answers are all numeric, but there still seems to be a problem with my query set. I receive the following error message 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([...])

The answers are all numeric, but there still seems to be a problem with my query set.

That's not a problem with your queryset. That is a problem with your model and database. If your values are numerical, you need to use an IntegerField , DecimalField , FloatField , or something else that stores data numerically in the database. For example:

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

Strictly speaking, you can convert it to numerical data in the database, but that is very unsafe, and will only let the modeling problem persist:

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

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

But it is a lot better to prevent ever entering non-numerical data in the database, than trying to mitigate the problem through queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM