如何在django-tables2中更改外部值的列标题?
模型
class Employer(models.Model):
name = models.CharField(verbose_name='Name', max_length=16)
class Employee(models.Model):
name = models.CharField(verbose_name='Name', max_length=16)
employer = models.ForeignKey(Employer, verbose_name='Employer')
表格
class EmployeeTable(tables.Table)
class Meta:
model = EmployeeTable
fields = ('name', 'employer.name')
输出
Name | Name
Bill | Steve
我想覆盖默认列标题以提供更有意义的信息。
首选输出
Employee name | Employer name
Bill | Steve
表格(不工作)
class EmployeeTable(tables.Table)
name = tables.Column(verbose_name='Employee name') # <-- Works!
employer.name = tables.Column(verbose_name='Employer name') # <-- Doesn't work!
class Meta:
model = EmployeeTable
fields = ('name', 'employer.name')
答案 0 :(得分:1)
我找到了解决方案。您必须使用Accessor
。
from django_tables2.utils import Accessor
class EmployeeTable(tables.Table)
name = tables.Column(verbose_name='Employee name')
employer_name = tables.Column(verbose_name='Employer name', orderable=False, accessor=Accessor('employer.name'))
class Meta:
model = EmployeeTable
fields = ('name', 'employer_name')