Reputation: 537
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.
Upvotes: 5
Views: 3459
Reputation: 4229
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
Upvotes: 6
Reputation: 42
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})
Upvotes: -2