我正在使用djangotables2在django中显示我的表格。我不想展示一个模型本身但更复杂的东西:一个查询对象,带有注释和计数以及更多的聚合函数。但是,在呈现表时,它仅显示模型的字段,而不显示查询对象的字段。好吧,我的模型也有新属性,所以它不是一个基本模型。不知道如何解决这个问题。
// view //
serial_number_list = TestSerialNumber.objects.filter(test_pool=test_pool).annotate(test_runs=Count('testrun')).order_by(o)
table = TestSerialNumberTable(serial_number_list)
RequestConfig(request).configure(table)
// models.py //
class TestSerialNumber(models.Model):
serial_number = models.ForeignKey("core.SerialNumber", on_delete=models.PROTECT)
test_pool = models.ForeignKey("TestPool", blank=True, null=True)
def __unicode__(self):
return self.serial_number.serial_number
def status(self):
try:
test_result = self.testresult_set.latest('report')
except TestResult.DoesNotExist:
return 'unknown'
else:
return test_result.test_status.name
class Meta:
db_table = 'ats2_serialnumber'
// tables.py //
import django_tables2 as tables
from ats2.models import TestSerialNumber
class TestSerialNumberTable(tables.Table):
class Meta(object):
model = TestSerialNumber
提前致谢!!!
答案 0 :(得分:1)
根据this,您需要在表类中添加这些字段(不在模型中但在查询集中添加):
import django_tables2 as tables
from ats2.models import TestSerialNumber
class TestSerialNumberTable(tables.Table):
test_runs= tables.Column()
class Meta(object):
model = TestSerialNumber
答案 1 :(得分:1)
你也可以试试这个,我已经测试过它的工作......
url(r'^ index_function_view /',index_function_view,name ='index_function_view'),
__author__ = 'ranvijay'
from django.shortcuts import render_to_response
import django_tables2 as tables
from django_tables2_reports.config import RequestConfigReport as RequestConfig
from django_tables2_reports.tables import TableReport
from django_tables2_reports.utils import create_report_http_response
from django.template import RequestContext
from test_app.models import Person
class PersonTable(TableReport, tables.Table):
class Meta:
model = Person
fields = ("id", "name", "active")
attrs = {"class": "paleblue"}
def index_function_view(request):
objs = Person.objects.filter(active=True)
table = PersonTable(objs)
table_to_report = RequestConfig(request).configure(table)
if table_to_report:
return create_report_http_response(table_to_report, request)
return render_to_response('person_list.html',
{'table': table},
context_instance=RequestContext(request))