Question

In using django-tables2 app, how can I get an additional column, which does not correspond to a column in my database, but rather is computed from them in a certain way. As a simple example, suppose I have the model:

#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)

so my model is basically three columns, the first two are numbers the third is the operation to be performed, either 'SUB', 'ADD'. For example:

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

Let's say I want a fourth column, computed from these three in the obvious way, namely it adds the two if the op is 'ADD' and subtracts if it is 'SUB'.

Finally, I have my 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')

How can I get django-tables2 to populate my results column? Is it through render? Perhaps something like

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

But my attempts at this have failed. In fact, even returning a constant with return 3.0, just left my fourth column blank.

Was it helpful?

Solution

If you add a new column and you populate the column using a render method, you need to add the empty_values attribute when defining the column.

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

Relevant Doc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top