2017-05-24 11:33:11 -04:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2016-07-20 10:07:32 -04:00
|
|
|
from django.db.models import Manager
|
|
|
|
|
|
|
|
|
|
|
|
class NaturalOrderByManager(Manager):
|
2018-06-11 15:10:31 -04:00
|
|
|
"""
|
|
|
|
Order objects naturally by a designated field. Leading and/or trailing digits of values within this field will be
|
|
|
|
cast as independent integers and sorted accordingly. For example, "Foo2" will be ordered before "Foo10", even though
|
|
|
|
the digit 1 is normally ordered before the digit 2.
|
|
|
|
"""
|
|
|
|
natural_order_field = None
|
2016-07-20 10:07:32 -04:00
|
|
|
|
2018-06-11 15:10:31 -04:00
|
|
|
def get_queryset(self):
|
2016-07-20 10:07:32 -04:00
|
|
|
|
2018-06-11 15:10:31 -04:00
|
|
|
queryset = super(NaturalOrderByManager, self).get_queryset()
|
2016-07-20 10:07:32 -04:00
|
|
|
|
|
|
|
db_table = self.model._meta.db_table
|
2018-06-11 15:10:31 -04:00
|
|
|
db_field = self.natural_order_field
|
2016-07-20 10:07:32 -04:00
|
|
|
|
2018-06-11 15:10:31 -04:00
|
|
|
# Append the three subfields derived from the designated natural ordering field
|
|
|
|
queryset = queryset.extra(select={
|
|
|
|
'_nat1': "CAST(SUBSTRING({}.{} FROM '^(\d{{1,9}})') AS integer)".format(db_table, db_field),
|
|
|
|
'_nat2': "SUBSTRING({}.{} FROM '^\d*(.*?)\d*$')".format(db_table, db_field),
|
|
|
|
'_nat3': "CAST(SUBSTRING({}.{} FROM '(\d{{1,9}})$') AS integer)".format(db_table, db_field),
|
2016-07-20 10:07:32 -04:00
|
|
|
})
|
2018-06-11 15:10:31 -04:00
|
|
|
|
|
|
|
# Replace any instance of the designated natural ordering field with its three subfields
|
|
|
|
ordering = []
|
|
|
|
for field in self.model._meta.ordering:
|
|
|
|
if field == self.natural_order_field:
|
|
|
|
ordering.append('_nat1')
|
|
|
|
ordering.append('_nat2')
|
|
|
|
ordering.append('_nat3')
|
|
|
|
else:
|
|
|
|
ordering.append(field)
|
2016-07-20 10:07:32 -04:00
|
|
|
|
|
|
|
return queryset.order_by(*ordering)
|