Home > Mobile >  Django model choices and jQuery DataTables sort
Django model choices and jQuery DataTables sort

Time:02-02

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" >
    <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>

CodePudding user response:

two solutions for cases like this:

  • I'm not that familiar with JavaScript 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)!

    UPDATE: apparently natsort does the job (from comments on this question)

  • You can parse text into a number before sorting. take a look at this question.

  • Related