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

问题描述 投票:0回答:1

我想找到一种方法来在 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> 
django html-table django-queryset
1个回答
0
投票

你可以使用 Django-query-to-table 包。

安装包:

pip install django-query-to-table

然后在您的视图或其他任何地方使用它:

from django.db import connection
from django_query_to_table import DjangoQtt
from django.http import HttpResponse

# view function in Django project
def listOfOrders(request):
  cursor = connection.cursor()
  reportTitle = "Order List"
  sqlQuery = "SELECT order_number as 'Order No', order_item as 'Item', total_amount 'Price', order_date as 'Date' FROM report_app_order"
  columnsToBeSummarized = ['Price']
  fontName = "Arial"
  cssClasses = "reportTable container"
  headerRowBackgroundColor = '#ffeeee'
  evenRowsBackgroundColor = '#ffeeff'
  oddRowsBackgroundColor = '#ffffff'
  table = DjangoQtt.generateFromSql(cursor, reportTitle, sqlQuery, columnsToBeSummarized, cssClasses, "ltr", fontName, "Total Price", True, headerRowBackgroundColor, evenRowsBackgroundColor, oddRowsBackgroundColor)

  # table is a string variable contianing the html table showing the query result
  return HttpResponse(table)

检查此链接:

https://mshaeri.com/blog/generate-html-table-report-from-sql-query-in-django/

© www.soinside.com 2019 - 2024. All rights reserved.