Search code examples
pythondjangodjango-tables2

How to change order_by dynamically using django-tables2?


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'

Solution

  • 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()
        ...