Django 表 2 创建自定义计算字段
Django tables 2 creating custom calculated fields
def calculateTotalVists(days):
total = 0
for i in days:
total += i
return total
class ClientTable(tables.Table):
class Meta:
model = Client
fields = ('id', 'name', 'phone')
attrs = {'class': 'table table-striped table-bordered', 'id': 'clients'}
客户端模型有一个字段"days",它是一个列表。我想创建一个自定义列,在天数传递到 calculateTotalVists() 后显示结果。但是我不知道如何使用函数访问器。
您不能使用随机函数并期望 tables2 神奇地将取自 table 记录的适当参数传递给它。只需在客户端模型上将其设为方法(或 属性)即可:
# models.py
class Client(models.Model):
# ...
def total_visits(self):
return sum(self.days) # or whatever self.days-based calculation
# tables.py
from django_tables2.utils import A
class ClientTable(tables.Table):
total_visits = Column(
accessor=A('total_visits'),
# ...
)
class Meta:
model = Client
fields = ('id', 'name', 'phone')
sequence = ('id', 'name', 'phone', 'total_visits')
# ...
def calculateTotalVists(days):
total = 0
for i in days:
total += i
return total
class ClientTable(tables.Table):
class Meta:
model = Client
fields = ('id', 'name', 'phone')
attrs = {'class': 'table table-striped table-bordered', 'id': 'clients'}
客户端模型有一个字段"days",它是一个列表。我想创建一个自定义列,在天数传递到 calculateTotalVists() 后显示结果。但是我不知道如何使用函数访问器。
您不能使用随机函数并期望 tables2 神奇地将取自 table 记录的适当参数传递给它。只需在客户端模型上将其设为方法(或 属性)即可:
# models.py
class Client(models.Model):
# ...
def total_visits(self):
return sum(self.days) # or whatever self.days-based calculation
# tables.py
from django_tables2.utils import A
class ClientTable(tables.Table):
total_visits = Column(
accessor=A('total_visits'),
# ...
)
class Meta:
model = Client
fields = ('id', 'name', 'phone')
sequence = ('id', 'name', 'phone', 'total_visits')
# ...