Search code examples
django-modelsoperator-precedencemetaslug

Django: How to get proper numerical ordering for a slug field?


The slug field definition and the ordering of the model is depicted below.

from models.py:

class Ayah(models.Model):
    suraya = models.SlugField(max_length=8,unique=True)

    class Meta:
    ordering = ['suraya']

However, there is an undesired result in the resulting order.

17-81-15    
17-82-15    
17-85-15    
2-186-2 
2-256-3

The desired ordering is the numerical order before the dash. So 2-whatever should come in order before 17-whatever .

There is probably a simple way to accomplish this through, maybe, regular expressions.


Solution

  • Depending on how much data you have, the easiest solution would be to add another column with only the leading number as an IntegerField() and then use it for sorting.

    class Ayah(models.Model):
        suraya = models.SlugField(max_length=8,unique=True)
        suraya_sort = models.IntegerField()
    
        class Meta:
            ordering = ['suraya_sort']
    

    Then overwrite the save() method to always store the first number to the sort column automatically.