【问题标题】:Calculating an average from survey input in a django template从 django 模板中的调查输入计算平均值
【发布时间】:2023-04-05 06:13:02
【问题描述】:

我正在尝试在 django 模板页面上显示调查结果。我无法根据特定的人口统计数据和每个类别的评分来显示平均值。我已经将调查响应数据以整数形式保存在我拥有的调查表单视图中。这是我目前为止剩下的:

#views.py
def statistics(request):
    male = Survey.objects.filter(gender='male')
    ...
    #Other demographics filtered
    ...

    def avgcalc(myDemographic, myCategory):
        ratings = []

        for x in myDemographic:
            ratings.append(myCategory)

        intTotal = 0
        intCount = 0
        intLenMyList = len(myDemographic)

        while(intCount <  intLenMyList):
            intTotal += ratings[intCount]
            intCount += 1

        return intTotal/intLenMyList
...
#rest of view rendering template, etc.

现在是我遇到问题的地方。如何根据人口统计轻松显示每个类别的数据?例如,在我的模板中我想做

#template.html
Demographic: Male
Total responses for this demographic: {{ male|length }}
Average response for specific category: {{ avgcalc(male, category) }}

{{ male|length }} 可以很好地显示男性受访者的数量,但是,在模板中,我不能使用 {{ avgcalc(male, category) }}。实际上,我已经设置了一个表格,并且大约有 20 个人口统计数据和十几个类别评级,所以如果可能的话,我希望避免将每一个都放在我的视图中(即 male_category_calc = avgcalc(male, category)对于每个人口统计和类别。这甚至可能吗,还是我需要做很长的路要走?我可以将每个人都输入到我的模板中,只要它有效。感谢任何帮助或建议。

【问题讨论】:

  • 是基于客户端的某种数据选择调用avgcalc,还是使用数据渲染整个页面?
  • 整个页面将与数据一起呈现。

标签: django django-templates python-2.7 django-views


【解决方案1】:

您可以使用custom template tag or filter 扩展模板功能。喜欢这个:

foo_app/templatetags/foo_tags.py:

from django import template
register = template.Library()

@register.filter
def avgcalc(myDemographic, myCategory):
    ratings = []

    for x in myDemographic:
        ratings.append(myCategory)

    intTotal = 0
    intCount = 0
    intLenMyList = len(myDemographic)

    while(intCount <  intLenMyList):
        intTotal += ratings[intCount]
        intCount += 1

    return intTotal/intLenMyList

然后在您的 template.html 中:

{% load foo_tags %}

{{ male|avgcalc:category }}

【讨论】:

  • 谢谢,但我无法确定它是否真的对我有用,因为显然这不是我对我想做的事情的唯一困惑。我现在似乎无法让我的大脑工作。因此,在包含要在表单上显示的人口统计字段的调查模型中,我还需要对不同的类别进行评级。我在想使用 male.categoryA 可以为 myCategory 指定类别,但它没有,所以当我尝试使用 {{ male|avgcalc:male.categoryA }} 它是不成功的。为了从男性那里获得 A 类的所有答案,我需要什么?
【解决方案2】:

你可以使用 django 的自定义模板标签来做到这一点。

要计算平均值,您可能需要查看 django 的 aggregation

它们具有 Avg 函数来计算特定字段的平均值。 (在你的情况下是类别)

from django.db.models import Avg
Model.objects.all().aggregate(Avg('attribute'))

【讨论】:

  • 这有点工作,但是有几个问题。首先,网页显示 {'categoryA__avg': 5.5} 而不仅仅是 5.5,其次,我必须在视图中输入每一个(例如 Model.objects.filter(gender="male").aggregate(Avg(' categoryA'))。有没有办法克服这两个问题?
  • 用类别作为参数创建一个函数。喜欢def calc_avg(category)。这是一个字典,所以通过在末尾添加['attribute_name__avg'] 来获取值。
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2021-01-31
  • 2019-07-06
  • 2023-03-19
  • 2018-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多