最近碰到一个需求,要对用户的学历进行排序,也就是按照['中专及以下', '高中', '大专', '本科', '硕士', '博士']的顺序进行排序,这就需要使用Django的ORM实现按指定字段的值进行排序。

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