我正在尝试创建一个通用表视图,它采用模型和列名元组,并显示模型的给定列。我的问题是内部 Meta 类。
假设这两个模型:
# models.py
from django.db import models
class Model_a(models.Model):
column_a_1 = models.Field()
column_a_2 = models.Field()
column_a_3 = models.Field()
column_a_4 = models.Field()
column_a_5 = models.Field()
class Model_b(models.Model):
column_b_1 = models.Field()
column_b_2 = models.Field()
column_b_3 = models.Field()
column_b_4 = models.Field()
column_b_5 = models.Field()
目标是有一个单一的视图来生成正确的表,其中一些列按给定的顺序排列。所以,我有一个这样的 urls.py:
# urls.py
from django.conf.urls import patterns, url
import myapp.views as myviews
import myapp.models as mymodels
urlpatterns = patterns( '',
url( r'^table_a/$',
myviews.show_table,
{ 'model': mymodels.Model_a,
'columns': ("column_a_1", "column_a_2", "column_a_3") } ),
url( r'^table_b/$',
myviews.show_table,
{ 'model': mymodels.Model_b,
'columns': ("column_b_5", "column_b_2") } ) )
还有一个像这样的简单views.py:
# views.py
from django.shortcuts import render
from django_tables2 import RequestConfig
import myapp.tables as mytables
def show_table(request, model, columns):
entries = model.objects.all()
table = mytables.ModelTable(entries, model, columns)
RequestConfig(request).configure(table)
return render(request, 'table_view.html', {'dynamic-table': table})
关键在 Tables.py 内的 Table 子类中:
# tables.py
from django_tables2 import import Table
class ModelTable(Table):
class Meta:
pass
def __init__(self, data, model, columns, order_by=None, orderable=None, empty_text=None,
exclude=None, attrs=None, sequence=None, prefix=None,
order_by_field=None, page_field=None, per_page_field=None,
template=None, sortable=None, default=None):
self.Meta.model = model
self.Meta.fields = columns
self.Meta.sequence = columns
super(ModelTable, self).__init__(data, order_by, orderable, empty_text,
exclude, attrs, sequence, prefix,
order_by_field, page_field, per_page_field,
template, sortable, default)
显然,我不明白如何从 Table 子类初始化程序中设置 Table.Meta 的属性。有趣的是,当我{% render_table dynamic-table %}
在模板中使用时,我得到一个空表(所以不可见),但是一个工作良好的分页器。
我的错误在哪里?