문제

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.

도움이 되었습니까?

해결책

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)

다른 팁

order_by is only method of QuerySet object, but not RawQuerySet. This one of limitation of uwsing Raw obeject in django orm

Why did you use raw query for so simple task? Try this:

Employees.objects.filter(deleted=0).order_by('-name')[:5]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top