Search code examples
pythondjangodjango-tables2

Django-tables2 column total


I'm trying to sum up all values from column using this documentation, but footer doesn't show up. I'm I missing something?

models.py

class Mokejimai(models.Model):
    id = models.AutoField(primary_key=True)
    nr = models.IntegerField(verbose_name='Mok. Nr.')
    data = models.DateField(verbose_name='Kada sumokėjo')
    suma = models.FloatField(verbose_name='Sumokėta suma')
    skola_pagal_agnum = models.FloatField(verbose_name='Skola pagal Agnum')
    date_entered = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Apmokėjimas įvestas')
    date_modified = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True)
    imone = models.ForeignKey(Imones, models.DO_NOTHING, verbose_name='Įmonė')
    sask = models.ForeignKey(Saskaitos, blank=True, null=True, verbose_name='Sąskaita')
    user = models.ForeignKey(User, models.DO_NOTHING, default=settings.AUTH_USER_MODEL)

tables.py

class MokejimaiTable(tables.Table):
    suma = tables.Column(footer=lambda table: sum(x['suma'] for x in table.data))

    class Meta:
        model = Mokejimai
        attrs = {"class": "paleblue"}
        fields = ('id', 'imone', 'sask', 'nr', 'suma', 'skola_pagal_agnum', 'data', 'date_entered')

Solution

  • Your screenshot shows that django-tables2 correctly assumes there is a footer on your table (yay!) but it seems that nothing is returned from the lambda. You can try to replace it by something like this to see what's going on:

    def suma_footer(table):
        try:
            s = sum(x['suma'] for x in table.data)
            print 'total:', s
        except Exception e:
            print str(e)
            raise
    
        return s
    
    
    class MokejimaiTable(tables.Table):
        suma = tables.Column(footer=suma_footer)
    
        class Meta:
            model = Mokejimai
            attrs = {"class": "paleblue"}
            fields = ('id', 'imone', 'sask', 'nr', 'suma', 'skola_pagal_agnum', 'data', 'date_entered')
    

    If something goes wrong while computing the sum, you should see a exception printed, if a value is computed, you should see 'total: ' printed.