[Answered ]-Django, how to make a query with [ORDER BY CONVERT (name USING gbk) ASC]

1👍

from django.db.models import Func, Value

class Convert(Func):
    def __init__(self, expression, transcoding_name, **extra):
         super(Convert, self).__init__(
             expression, transcoding_name=Value(transcoding_name), **extra)

    def as_mysql(self, compiler, connection):
        self.function = 'CONVERT'
        self.template = '%(function)s(%(expressions)s AS %(transcoding_name)s)'
        return super(Conver, self).as_sql(compiler, connection)

Usage:

queryset.order_by(Convert('name', 'gbk').asc())

Documentation:

1👍

you can use extra

queryset.extra(
    select={'convert_name': 'convert(name using gbk)'}, 
    order_by=['convert_name']
)

Leave a comment