Search code examples
pythondjangowebdjango-tables2

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

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.


Solution

  • 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')
            # ...