5

My table class looks pretty typical except that maybe it includes a before_render() function. What's great about before_render is that I can access self. This gives me access to dynamic information about the model I'm using. How can I access dynamic information (like from before_render) to change the order_by variable in the Meta class?

def control_columns(table_self):
    # Changes yesno for all Boolean fields to ('Yes','No') instead of the default check-mark or 'X'.
    for column in table_self.data.table.columns.columns:
        current_column = table_self.data.table.columns.columns[column].column
        if isinstance(current_column,tables.columns.booleancolumn.BooleanColumn):
            current_column.yesno = ('Yes','No')

class DynamicTable(tables.Table):
    def before_render(self, request):
        control_columns(self)

    class Meta:        
        template_name = 'django_tables2/bootstrap4.html'
        attrs = {'class': 'custom_table', 'tr': {'valign':"top"}}
        order_by = 'index'
Liam Hanninen
  • 1,525
  • 2
  • 19
  • 37

1 Answers1

2

So it seems a little bit weird, but it works

class DynamicTable(tables.Table):
    ...
    def before_render(self, request):
        self.data.data = self.data.data.order_by('id')
        self.paginate()
    ...
Anton Pomieshchenko
  • 2,051
  • 2
  • 10
  • 24
  • This works great - and it overwrites or runs after Meta so I can leave order_by in Meta as a default and then overwrite when I want in before_render. Thanks! – Liam Hanninen Apr 15 '20 at 00:50