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

时间:2016-02-11 06:52:27

标签: python mysql angularjs django

您正在开发python-django(v1.6)项目,我需要提供一个表,其中包含数据库中的数据。我已经准备好了我的模板和模板。 我的观点

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 %}

根据我的代码,不知道为什么名称没有显示。如何从数据库中获取数据(特定列)并在表中显示?使用AngularJS更好的方法?在此先感谢你们

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

阅读Django Querysets应该可以帮助你https://docs.djangoproject.com/en/1.9/ref/models/querysets/

将查询集传递给渲染函数中的模板,并在模板中迭代它将显示所有数据。