如何从数据库中获取所有数据并显示在table

How to get all the data from the database and display in a table

大家好,我正在做一个 python-django(v1.6) 项目,我需要想出一个 table,其中包含我数据库中的数据。我已经准备好了我的 templeteview 和模板。 我的观点

class MyView(TemplateView):
    model = Mymodel
    template_name = "home.html"

    def get_context_data(self, *args, **kwargs):
        context = super(MyView, self).get_context_data(*args, **kwargs)
        context['ngapp'] = "Myapp"
        return context

    def get_data(request):
        query_results = Mymodel.objects.objects.all()

我的html

{% extends "base.html" %}

<!--Page heading-->
{% block page_title %}My home{% endblock %}
<!---->

{% block content %}
<div>
    <table class="table">
        <tr>
            <th>Name</th>
        </tr>
        {% for item in query_results %}
            <tr>
                <td> {{ item.name}}</td>
            </tr>
        {% endfor %}
    </table>


</div>
{% endblock %}

根据我的代码,不知道为什么不显示名称。如何从我的数据库中获取数据(特定列)并将其显示在 table 中?使用 AngularJS 更好的方法?提前谢谢大家

阅读 Django 查询集应该对您有所帮助 https://docs.djangoproject.com/en/1.9/ref/models/querysets/

在渲染函数中将查询集传递给您的模板并在模板中对其进行迭代将显示您的所有数据。

您没有将查询集传递给模板。像这样尝试:

class MyView(TemplateView):
    model = Mymodel
    template_name = "home.html"

    def get_context_data(self, *args, **kwargs):
        context = super(MyView, self).get_context_data(*args, **kwargs)
        context['ngapp'] = "Myapp"
        context['query_results'] = self.get_data()
        return context

    def get_data(self):
        query_results = self.model.objects.all()
        return query_results