python - 从其他列计算列 django-tables2

标签 python django django-tables2

在使用django-tables2应用程序时,如何获得一个附加列,该列与我的数据库中的列不对应,而是以某种方式根据它们计算出来。作为一个简单的例子,假设我有以下模型:

#models.py
class AddSub(models.Model)

    num1 = models.DecimalField(max_digits=6, decimal_places=2)
    num2 = models.DecimalField(max_digits=6, decimal_places=2)
    op = models.CharField(max_length=3)

所以我的模型基本上是三列,前两列是数字,第三列是要执行的操作,“SUB”、“ADD”。例如:

num1 |num2| op
1.01  5.67  'ADD'
87.3  23.4  'SUB'
.
.
.

假设我想要第四列,以明显的方式从这三列计算出来,即如果操作是“ADD”,则将两列相加;如果操作是“SUB”,则将两列相减。

最后,我有我的 table :

class CalcTable(tables.Table)
    num1 = tables.Column(verbose_name='Operand 1')
    num2 = tables.Column(verbose_name='Operand 2')
    operation = tables.Column(verbose_name='Operation')
    result = tables.Column(verbose_name='The Result')

如何让 django-tables2 填充我的结果列?是通过渲染吗?也许类似

def render_result(self, value, record):
   #add up 

但是我的尝试失败了。事实上,即使使用 return 3.0 返回一个常量,也只是将第四列留空。

最佳答案

如果您添加新列并使用 render 方法填充该列,则需要在定义列时添加 empty_values 属性。

 result = tables.Column(verbose_name='The Result', empty_values=())

Relevant Doc

关于python - 从其他列计算列 django-tables2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132477/

相关文章:

python - 将列添加到查询集和 django-table2 表

python - 在 python 中倾斜或剪切图像

python - 从 python 中的字符串中删除除 URL 之外的所有内容

python - 如何在 python/django 中使用 URL 保存图像

django - 获取外键的ID

Django tables2 - 如何在页面加载时对表格列进行排序?

python - Mongoengine + Django-tables2 : Expected table or queryset, 不是查询集

python - NetworkX-如何更改节点的形状?

python - 在 python 中检查字典中的键的正确方法

python - Django 枪兽 : Error when calling the metaclass bases