Forums

Django order_by() is not working for me.

For some reason order_by() is not working for me on a queryset. I've tried everything I can think of, but my Django/MySQL installation doesn't seem to be doing anything with order_by() method. The list appears to just remain in a fairly unordered state, or is ordered on some basis I cannot see.

My Django installation is 1.8.

An example of one of my models is as follows:

class PositiveTinyIntegerField(models.PositiveSmallIntegerField):
    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            return "tinyint unsigned"
        else:
            return super(PositiveTinyIntegerField, self).db_type(connection)

class School(models.Model):
    school_type = models.CharField(max_length=40)
    order = PositiveTinyIntegerField(default=1)

# Make the identity of db rows clear in admin
def __str__(self):
    return self.school_type

And here is the the relevant line from my view:

schools = School.objects.order_by('order')

At first I thought the problem was related to having used the non-standard PositiveTinyIntegerField() defined by a class I found on a website somewhere which allows me to use the MySQL Tiny Integer field. However, when I ordered by 'id', or 'school_type' the list still remained in an ordered that appeared fairly random to my eye.

I could put in my own loop which orders the queryset after it has been retrieved, but I'd really rather solve this issue so I can use the standard Django way of doing it.

I hope someone can see where the issue may be coming from.

The important things here are: What does the data look like and are you actually running the code you think you're running.