5

I'm using django tables2 to render data in table form. I want the table to be sorted by column1 as default when page loading. The sort is working on clicking the column but I want this to be sorted by default on page loading.

2 Answers2

6

The Table constructor has an order_by-argument. You can use that to set initial ordering.

import django_tables2 as tables

class Table(tables.Table):
    first_name = tables.Column()
    last_name = tables.Column()


def view(request):
    table = Table(data, order_by='last_name')

    return render(request, 'template.html', {'table': table})

This option is also available in Table's class Meta:

class Table(tables.Table):
    first_name = tables.Column()
    last_name = tables.Column()

    class Meta:
        order_by = '-last_name'  # use dash for descending order
Jieter
  • 4,101
  • 1
  • 19
  • 31
  • This is sorting my table but other sorting fields not working. only the lastname is sorted – Suresh Jaganathan Jun 07 '16 at 05:57
  • You can also pass a tuple of columns to sort on. But that's not the question you asked. – Jieter Jun 07 '16 at 07:11
  • I asked for working table sorting. When I give order_by, the table displaying as ordered_by lastname. And by default the sort icon (down arrow) for lastname column is selected. In such case, if we select some other column, the sort is not working. If we remove the order_by, the sorting on other columns also working fine. – Suresh Jaganathan Jun 07 '16 at 08:05
  • I want default sorting not ordering – Suresh Jaganathan Jun 07 '16 at 08:05
  • I'm not sure what you mean by 'sorting, not ordering', but adding an `order_by` argument to the table constructor should not prevent you from changing the ordering by clicking on a column. Can you share your code? – Jieter Jun 07 '16 at 08:12
  • I used similar to your comments table = Table(data, order_by='last_name') and tried table.order_by = 'last_name' also. This is displaying the table by default sorting/ordering as 'last_name'. But when I click on other columns, the sorting is not happening and it still (sorting) highlighting 'last_name' column only – Suresh Jaganathan Jun 07 '16 at 08:14
  • And without the `order_by`, you can sort on the other columns? Hard to see what's going on, just tested with the django-tables2 example project and it worked like charm. – Jieter Jun 07 '16 at 08:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113997/discussion-between-suresh-jaganathan-and-jieter). – Suresh Jaganathan Jun 07 '16 at 08:22
-2

If your database is SQLite, try:

results = model_name.objects.extra(select={'model_field':'CAST(model_field AS INTEGER)'}).order_by('model_field')
return render(request, template_name, {"results":results})
uajain
  • 42
  • 2
  • The question is about sorting the rendered table for django-tables2, not regular querysets. – Jieter Jun 06 '16 at 10:28