首页 > 解决方案 > 我想将 django QUERY 表示为 html 页面中的表格,表格标题与 django 字段名称相同。我该如何实施?

问题描述

我想找到一种在 HTML 表上表示通过 SQL 查询获得的记录集的方法。我查阅了之前的一篇文章,该文章谈到了与我的类似问题,但在那篇文章中提到了一个模型,但我无法使其适应我的需求。我想调整该帖子的解决方案,以便即使在我使用 SQL 查询时它也能正常工作。

有可能吗?帖子是这样的:

我想将 django 模型表示为 html 页面中的表格,表格标题与 django 字段名称相同。我该如何实施?

这是我的看法:

def posts_discussione(request,pk):
discussione = Discussione.objects.get(pk=pk)
posts = Post.objects.raw(f'SELECT * from forum_post where discussione_id = {pk} order by dataCreazione ASC')
context = {'posts':posts,'discussione':discussione}
return render(request,'posts-discussione.html',context)

这是我的 HTML 代码:

     <table>
        <thead>
            <th>Autore</th>
            <th>Data</th>
            <th>Contenuto</th>
        </thead>
        <tbody>
        {% for post in posts %}
            <tr>
                <td>{{post.autorePost}}</td>
                <td>{{post.dataCreazione}}</td>
                <td>{{post.contenuto}}</td>
        {% endfor %}
        </tbody>
    </table> 

标签: djangohtml-tabledjango-queryset

解决方案


推荐阅读