django orm order_by 根据汉字首字母排序 [ORDER BY CONVERT(name USING gbk)ASC]查询
2021-06-11 01:04
标签:self desc value 框架 expr rgba super from question 首先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文件 def as_mysql(self, compiler, connection): 用法: 如遇到其他问题,请加群讨论 django orm order_by 根据汉字首字母排序 [ORDER BY CONVERT(name USING gbk)ASC]查询 标签:self desc value 框架 expr rgba super from question 原文地址:https://www.cnblogs.com/chaihy/p/14240081.htmlfrom 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)
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())
文章标题:django orm order_by 根据汉字首字母排序 [ORDER BY CONVERT(name USING gbk)ASC]查询
文章链接:http://soscw.com/essay/93371.html