Search code examples
djangosql-order-bymodels

The raw query in django 1.5 doesn't work with order by desc


from project.models import Employees
sorting_field = 'name'
emps = Employees.objects.raw('SELECT * FROM employees where deleted=0 order by %s desc limit 5', [sorting_field])

This doesn't get the order of records in descending order.


Solution

  • Providing the value of order by %s via the param argument to .raw() won't work because all the params are escaped by the database backend. Therefore you'll end up with a query like order by 'name' (note the quotes) which won't work.

    Alternatively, you could use string formatting (which the Django docs strongly and rightely so advise against) but if you don't use it to put user generated input into the query, you should be fine:

    if condition:
        sort_field = 'name'
    else:
        sort_field = 'id'
    
    query = 'SELECT * FROM employees WHERE deleted = 0 ORDER BY {} DESC LIMIT 5'
    params = {…}  # other parameters that need regular escaping
    emps = Employees.objects.raw(query.format(sort_field), params)