Search code examples
djangosql-order-bydjango-querysetspecial-characters

Django: How to handle special chars in order_by


I need to order a django queryset by a list of columns. Some of them contain the minus char like IP-A.

Now Django complains about invalid argument(s).

What is the right way to handle columns with those chars? Renaming the columns is not an option, as the model is fix.


Solution

  • Normally the name of the fields that Django uses are the variables you define in the model classes. These are, unless you use some sophisticated trics, valid Python identifiers, and these can not contain a hyphen (-).

    One can use the db_column=… parameter [Django-doc] to translate the name of the fields in the Django model to different column names at the database. For example:

    class MyModel(models.Model):
        ip_a = models.CharField(max_length=128, db_column='IP-A')

    In the Django ORM and in almost all interactions with the model object, the name of the column at the database side can however be seen as a "technical detail". The ORM works with the name of the field. So you can sort your model objects with:

    MyModel.objects.order_by('ip_a')

    The ORM will make the translation to the real database columns, and thus sort behind the curtains on the IP-A column.