gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:27:59 26 4
gpt4 key购买 nike

我想使用 [ORDER BY CONVERT (name USING gbk) ASC] 进行查询,以便管理员更改/添加表单中的 foreignkey 列表可以按以下方式排序汉语拼音,可能吗?

数据库: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 中尝试了以下 2 种方法,但都不起作用

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: Cannot resolve keyword 'CONVERT (name USING gbk)' into field. Choices are: commoninfo_ptr, commoninfo_ptr_id, first_name, id, last_name, name, profile, Check fields/fieldsets/exclude attributes of class ProfileAdmin.

最佳答案

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())

文档:

关于mysql - Django,如何使用 [ORDER BY CONVERT (name USING gbk) ASC] 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com