如何使用django-tables2动态更改order_by?

问题描述 投票:5回答:1

我的表类看起来很典型,除了它可能包含一个before_render()函数。 before_render的优点是我可以访问self。这使我可以访问有关所用模型的动态信息。如何访问动态信息(例如from before_render)来更改Meta类中的order_by变量?

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'
python django django-tables2
1个回答
2
投票

所以似乎有点不可思议,但是有效

class DynamicTable(tables.Table):
    ...
    def before_render(self, request):
        self.data.data = self.data.data.order_by('id')
        self.paginate()
    ...
© www.soinside.com 2019 - 2024. All rights reserved.