这是一个使用 Django_Pandas 和“扩展引导表”(https://github.com/wenzhixin/bootstrap-table) 的最小但优雅的解决方案
优雅之处在于能够将 Pandas DataFrame 导出为 JSON,并让 Bootstrap Table 脚本使用该 JSON 内容。
HTML 表格是为我们编写的,我们不需要担心(看看下面我们只包含 'table' 标记而不自己编写行,甚至是 for 循环.) 它是交互式的。 Bootstrap 让它看起来很漂亮。
要求:Bootstrap、JQuery、Django_Pandas、wenzhixin/bootstrap-table
models.py
from django.db import models
from django_pandas.managers import DataFrameManager
class Product(models.Model):
product_name=models.TextField()
objects = models.Manager()
pdobjects = DataFrameManager() # Pandas-Enabled Manager
views.py
from models import Product
def ProductView(request):
qs = Product.pdobjects.all() # Use the Pandas Manager
df = qs.to_dataframe()
template = 'product.html'
#Format the column headers for the Bootstrap table, they're just a list of field names,
#duplicated and turned into dicts like this: {'field': 'foo', 'title: 'foo'}
columns = [{'field': f, 'title': f} for f in Product._Meta.fields]
#Write the DataFrame to JSON (as easy as can be)
json = df.to_json(orient='records') # output just the records (no fieldnames) as a collection of tuples
#Proceed to create your context object containing the columns and the data
context = {
'data': json,
'columns': columns
}
#And render it!
return render(request, template, context)
product.html
<script src='/path/to/bootstrap.js'>
<script src='/path/to/jquery.js'>
<script src='/path/to/bootstrap-table.js'>
<script src='/path/to/pandas_bootstrap_table.js'>
<table id='datatable'></table>
<!-- Yep, all you need is a properly identified
but otherwise empty, table tag! -->
pandas_bootstrap_table.js
$(function() {
$('#datatable')({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
columns: {{ columns|safe }}, // here is where we use the column content from our Django View
data: {{ data|safe }}, // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
});
});