2016-09-22 58 views
0

如何在django-tables2中更改外鍵值的列標題?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

我找到一個解決方案。你必須使用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')