Django model choices and jQuery DataTables sort

I am struggling to get a sorting to work in jQuery DataTables when I want to sort objects based on choices in the django model. With the snippets included I can sort it based on the values 1..n in choices, but as it considers those as strings, sorting is not working properly. It considers 10, 11 and 12 to be lower that everything between 2 to 9. How would I fix this issue?

I have this model in my django app:

class Action(models.Model):

    STATUS_CHOICES = (
        ('1', 'Status 1'),
        ('2', 'Status 2'),
        ('3', 'Status 3'),
        ('4', 'Status 4'),
        ('5', 'Status 5'),
        ('6', 'Status 6'),
        ('7', 'Status 7'),
        ('8', 'Status 8'),
        ('9', 'Status 9'),
        ('10', 'Status 10'),
        ('11', 'Status 11'),
        ('12', 'Status 12'),
    )

    status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=1, verbose_name='Status')

From views I will render everything to my template:

def actions_view(request, *args, **kwargs):

    actions = Action.objects.all()

    context = {
        'actions':actions,
    }

    return render(request, "actions.html", context)

And in the template everything will be displayed in jQuery datatables:

<table id="actionTable" class="table table-striped">
    <thead>
        <tr>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for action in actions %}
            <tr>
                <td><span style="display:none;">{{ action.status }}</span>{{ action.get_status_display }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

<script>
    $(document).ready(function () {
        $('#actionTable').DataTable({
            fixedHeader: false,
            paging: false,
            searching: false,
            info: false,

            "language": {
                "zeroRecords": "No action",
            },
        });
    });
</script>

Here are three solutions:

  1. Normally you can trick Django templates to convert strings into integers by adding 0 to the string, using built-in add filter (doc, SO). Here is an example:

    {{ my_string|add:"0" }}
    
  2. Do as seen here. This way you can use integers instead of strings containing numbers in your STATUS_CHOICES. Here is an example:

    One = 1
    
    STATUS_CHOICES = {
        (One, 'Status 1')
    }
    
  3. I'm not that familiar with JS but I'm confident that you can find some plugins to handle cases like this. Just look how this plugin handles ordered numbers (1st, 2nd, ...) in sorting (from SO)!

Back to Top