我有一张这样的桌子:
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
答案 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
您的“自定义列”示例示例也应该起作用。