2
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'}

The client model has the field "days" which is a list. I would like to create a custom column which displays the result after days is passed into calculateTotalVists(). However I'm not how I can use accessors with functions.

user3080600
  • 1,309
  • 2
  • 11
  • 23

1 Answers1

7

You can't use a random function and expect tables2 to magically pass it the appropriate arguments taken form the table record. Just make it a method (or property) on the client model:

# 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')
        # ...
user2390182
  • 72,016
  • 6
  • 67
  • 89