Provide an optional attribute to trigger a sort of the ouput listview fixes #303

This commit is contained in:
Joel 2016-07-15 20:58:05 -07:00
parent 46da9866e3
commit 7da7ff79b7
2 changed files with 9 additions and 0 deletions

View File

@ -66,6 +66,7 @@ class SiteListView(ObjectListView):
queryset = Site.objects.all()
filter = filters.SiteFilter
table = tables.SiteTable
sorting_attribute = 'name'
template_name = 'dcim/site_list.html'

View File

@ -1,3 +1,6 @@
from natsort import natsorted
from operator import attrgetter
from django_tables2 import RequestConfig
from django.contrib import messages
@ -25,6 +28,7 @@ class ObjectListView(View):
filter = None
filter_form = None
table = None
sorting_attribute = None
edit_permissions = []
template_name = None
redirect_on_single_result = True
@ -68,6 +72,10 @@ class ObjectListView(View):
# Provide a hook to tweak the queryset based on the request immediately prior to rendering the object list
self.queryset = self.alter_queryset(request)
# If the sorting attribute is set, sort the final result based on the provided attribute key
if self.sorting_attribute:
self.queryset = natsorted(self.queryset, key=attrgetter(self.sorting_attribute))
# Construct the table based on the user's permissions
table = self.table(self.queryset)
table.model = model