如何以列格式打印数据库中的数据?

时间:2017-03-13 19:38:51

标签: python django sqlite

我创建了一个models.py文件并为我的表创建了一种格式。如何在下面的网页上打印出来。在此之后,我想将它与数据库中的其他数据进行比较。输入的数据通过1-4的范围内的单选按钮完成(附加数据库布局的一个例子)。我相信使用类似于Objects.get的东西?我错了enter image description here

models.py

class Question(models.Model):
    name = models.CharField(max_length=10, primary_key=True)
    question1 = models.CharField(max_length=50, choices=Question1_CHOICES)
    question2 = models.CharField(max_length=50, choices=Question2_CHOICES)
    question3 = models.CharField(max_length=50, choices=Question3_CHOICES)
    question4 = models.CharField(max_length=50, choices=Question4_CHOICES)
    question5 = models.CharField(max_length=50, choices=Question5_CHOICES)
    question6 = models.CharField(max_length=50, choices=Question6_CHOICES)
    question7 = models.CharField(max_length=50, choices=Question7_CHOICES)
    question8 = models.CharField(max_length=50, choices=Question8_CHOICES)
    question9 = models.CharField(max_length=50, choices=Question9_CHOICES)
    question10 = models.CharField(max_length=50, choices=Question10_CHOICES)`

我还添加了views.py,它存储数据以防万一。

Views.py

def question1(request):
    question_form1 = QuestionForm1
    if request.method == 'POST':
        form = QuestionForm1(request.POST)
        if form.is_valid():
            form.save()  # saves to database
            return render(request, 'music/compare.html')
        else:
            return render(request, 'music/failed.html')
    return render(request, 'music/question1.html', locals())

1 个答案:

答案 0 :(得分:1)

查询表中的所有行:

ModelName.objects.all()

然后你可以将它传递给你的观点:

return render(request, 'music/compare.html', {
  "rows": Question.objects.all()
})

并使用模板中的行:

<table>
  <th>
    <!-- Do your headers here -->
  </th>
{% for row in rows %}
  <tr>
    <td>{{row.name}}</td>
    <td>{{row.question1}}</td>
    <td>{{row.question2}}</td>
    ...
  </tr>
{% endfor %}
</table>