django中按照指定字段的值排序

1、 MySQL中的SQL语句的语法:

select * from user_education where user_id = 1 ORDER BY FIELD(degree, '中专及以下', '高中', '大专', '本科', '硕士', '博士') DESC

2、python代码

ordering = 'FIELD(`degree`, {})'.format(','.join([ "'{}'".format(i) for i in educations])) 

education_last = Education.objects.filter(user_id=user['id']).extra(select={'ordering': ordering}, order_by=('-ordering',))

可通过数据库日志看到生成的sql语句:

SELECT (FIELD(`degree`, '中专及以下','高中','大专','本科','硕士','博士')) AS `ordering` FROM `user_education` WHERE `user_education`.`user_id` = 31 ORDER BY `ordering` DESC LIMIT 1

转载自:http://www.zgljl2012.com/django-querysetshi-xian-an-zhi-ding-zi-duan-de-zhi-jin-xing-pai-xu/

你可能感兴趣的:(django中按照指定字段的值排序)