首先mysql sql语句查询公司名称首字母排序如下:
SELECT * FROM `表名` ORDER BY CONVERT (company USING gbk) Desc;
django框架用orm查询
models.Contacts.objects.all().order_by('CONVERT (company USING gbk)')
这样直接排序会报错:
FieldError: Cannot resolve keyword 'CONVERT (name USING gbk)' into field
所以这种方式行不通,但我们又不想用sql查询
看到这位网友提醒:
http://cn.voidcc.com/question/p-zzfegywi-sk.html
此方法写法有误,已修改
总结如下:
models.py文件
from django.db.models import Func, Value
class Convert(Func):
def __init__(self, expression, transcoding_name, **extra):
super(Convert, self).__init__(
expression=expression, transcoding_name=transcoding_name, **extra)
def as_mysql(self, compiler, connection):
self.function = 'CONVERT'
self.template = ' %(function)s(%(expression)s USING %(transcoding_name)s)'
return super(Convert, self).as_sql(compiler, connection)
用法:
order_by(models.Convert('company', 'gbk').asc())
order_by(models.Convert('company', 'gbk').desc())
如遇到其他问题,请加群讨论