覆盖相关字段的`render_FOO`

时间:2018-08-23 14:47:34

标签: django django-tables2

我有一张这样的桌子:

import django_tables2 as tables
from .models import MyModel

class MyTable(tables.Table):
    class Meta:
        model = MyModel
        fields = ['myfield', 'relatedtable.otherfield']

由于我无法使用render_relatedtable.otherfield并且render_relatedtable__otherfield不起作用,如何为render_<column_name>覆盖value_<colum_name>relatedtable.otherfield?甚至有可能吗?


我尝试了以下方法,但没有一个起作用:

覆盖__init__()中的属性

class MyTable(tables.Table):
    class Meta:
        model = MyModel
        fields = ['myfield', 'relatedtable.otherfield']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.columns['relatedtable.otherfield'].render = myrenderfnc
        # and/or
        self.columns['relatedtable.otherfield'].column.render = myrenderfnc

自定义列

class MyColumn(tables.Column):
    def render(self, record):
        return getattr(record, 'relatedtable.otherfield')

class MyTable(tables.Table):
    class Meta:
        model = MyModel
        fields = ['myfield']

    otherfield = MyColumn()

“重命名”列

class MyTable(tables.Table):
    class Meta:
        model = MyModel
        fields = ['myfield']

    def __init__(self, *args, **kwargs):
        exclude = ['relatedtable.otherfield']
        extra_columns = [('otherfield', self.base_columns['relatedtable.otherfield')]
        super().__init__(*args, exclude=exclude, extra_columns=extra_columns, **kwargs)
        self.columns['relatedtable.otherfield'].render = myrenderfnc
        # and/or
        self.columns['relatedtable.otherfield'].column.render = myrenderfnc

1 个答案:

答案 0 :(得分:0)

一种方法是使用访问器显式定义列,然后在您的render_FOO方法名称中使用列名,如下所示:

class MyTable(tables.Table):
    otherfield = MyColumn(accessor='relatedtable.otherfield')

    class Meta:
        model = MyModel
        fields = ['myfield']

    def render_otherfield(self, record, value):
        return value

您的“自定义列”示例示例也应该起作用。