Search code examples
djangodjango-tables2

Is there a way to always order a table by a specific column in django-tables2?


I'm using django-tables2 to render a table of MyModel. MyModel has a few different categories specified by its category field. I want to be able to overwrite order_by such that the table's primary ordering is always category and anything else selected is just a secondary ordering. Any suggestions on how I might do this?


Solution

  • For anyone else with this issue, I eventually got to an answer:

    class PersonTable(tables.Table):
        def __init__(self, *args, **kwargs):
            def generate_order_func(field_name: str) -> Callable:
                # django-tables2 stamps any secondary ordering if you have a custom ordering function on any of your
                # ordering fields. This adds custom ordering to every field so that name is always the primary
                # ordering 
    
                def order_func(qs: QuerySet, descending: bool) -> Tuple[QuerySet, bool]:
                    # Need custom ordering on deal_state (not alphabetical)
                    qs = qs.order_by("name", ("-" if descending else "") + field_name)
                    return qs, True
    
                return order_func
    
            for field in self._meta.fields:
                setattr(self, f"order_{field}", generate_order_func(field))
    
            super().__init__(*args, **kwargs)
    

    This overwrites the ordering for each field such that it's ordered by the primary ordering firt.