Django,如何使用[ORDER BY CONVERT(名称USING gbk)ASC]进行查询

时间:2016-07-22 03:34:43

标签: mysql django

我想用[ORDER BY CONVERT (name USING gbk) ASC]进行查询,以便管理员更改/添加表单中的foreignkey列表可以按中文拼音排序,是否可以?

DB:mysql, 样本类是打击的(表commoninfo:utf8_general_ci的字符集):

class CommonInfo(models.Model):
    name = models.CharField(max_length=128)
    def __str__(self):
        return self.name

class Personal(CommonInfo):
    first_name = models.CharField(max_length=128,null=True, blank=True, default = None)
    last_name = models.CharField(max_length=128,null=True, blank=True, default = None)

class Profile(models.Model):
    personal_info = models.ForeignKey(Personal, null=True, blank=True, default = None)
    mobile = models.CharField(max_length=32,default='',null=True, blank=True)

我在ProfileAdmin中尝试了以下两种方法,但两种方法都不起作用

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "personal_info":    

        #raw_sql = 'SELECT id as commoninfo_ptr_id, name FROM share_commoninfo ORDER BY CONVERT (name USING gbk) ASC'
        #raw_querySet = Personal.objects.raw(raw_sql) 
        #kwargs["queryset"] = raw_querySet

        querySet = Personal.objects.extra(order_by=['CONVERT (name USING gbk)'])
        kwargs["queryset"] = querySet

        return super(ProfileAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

admin.site.register(models.Profile, ProfileAdmin)
  

FieldError:无法解析关键字' CONVERT(名称使用gbk)'成   领域。选项包括:commoninfo_ptr,commoninfo_ptr_id,first_name,id,   last_name,name,profile,Check fields / fieldsets / exclude属性   class ProfileAdmin。

2 个答案:

答案 0 :(得分: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)

用法:

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

文档:

答案 1 :(得分:0)

您可以使用extra

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