如何在django中进行统计

时间:2018-04-12 15:38:23

标签: django

我使用django fobi允许用户创建自己的表单。我想根据这些表格制作一些报告和统计数据。

我有一个有效的python代码,但我不知道如何翻译" django工作模板中的代码。

数据如下:

saved_data = '''
  [
       [{
           "label": "Question 1?",
           "html_name": "question_1",
           "first_name": "John",
           "last_name": "Doe",
           "email": "john@doe.com",
           "answer": "Yes"
         }, {
           "label": "Question 2?",
           "html_name": "question_2",
           "first_name": "John",
           "last_name": "Doe",
           "email": "john@doe.com",
           "answer": ["Red", "White"]
       }],
       [{
           "label": "Question 1?",
           "html_name": "question_1",
           "first_name": "Jane",
           "last_name": "Mary",
           "email": "mary@jane.com",
           "answer": "No"
         }, {
           "label": "Question 2?",
           "html_name": "question_2",
           "first_name": "Jane",
           "last_name": "Mary",
           "email": "mary@jane.com",
           "answer": ["Red", "Black"]
         }]
  ]

'''

data = json.loads(saved_data)

answer = {}

for x in data:
    for y in x:
        if type(y['answer']) is list:
            for an in y['answer']:
                answer.setdefault(y['label'], {})\
                    .setdefault('answer', []).append(an)
                answer.setdefault(y['label'], {}).setdefault('full_name', []).append(y['first_name'] + ' ' + y['last_name'])
                answer.setdefault(y['label'], {}).setdefault('email', []).append(y['email'])
        elif type(y['answer']) is str:
            answer.setdefault(y['label'], {})\
                .setdefault('answer', []).append(y['answer'])
            answer.setdefault(y['label'], {}).setdefault('full_name', []).append(y['first_name'] + ' ' + y['last_name'])
            answer.setdefault(y['label'], {}).setdefault('email', []).append(y['email'])

for questions, answers in answer.items():
    print('\n', questions)
    counting = Counter(answers['answer'])
    for key, value in counting.items():
        print(key, value)
        for answer in zip(answers['full_name'], answers['answer']):
            if key == answer[1]:
                print(answer[0])

如何让它在django 1.11模板中运行?

1 个答案:

答案 0 :(得分:1)

您需要将其从template传递到view。例如,您可以使用基于函数的视图来包装该逻辑并将其放在views.py中。您必须在urls.py中添加路由并使该视图返回模板。

在模板中,您可以for循环播放答案项目,然后根据需要显示它们。