Lea*_*mer 10 python mysql django orm
最近开始使用Django ORM.I想要执行此查询
select student_id from students where student_id like "%97318%" order by CAST(student_id as UNSIGNED) desc;
Run Code Online (Sandbox Code Playgroud)
其中student_id是一个CharField,我想将其作为整数进行查询.我试过了
students.objects.filter(student_id__contains "97318").order('-student_id')
Run Code Online (Sandbox Code Playgroud)
工作良好.但是不知道也无法找到如何将"student_id"转换为int,就像上面用"Django ORM"提到的实际MySQL查询一样.我应该使用原始查询还是有出路?让我知道你的建议.
eri*_*eed 28
不需要使用的更新替代方案extra是强制转换函数(Django 1.10中的新增功能):
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cast
>>> Value.objects.create(integer=4)
>>> value = Value.objects.annotate(as_float=Cast('integer', FloatField())).get()>
>>> print(value.as_float)
4.0
Run Code Online (Sandbox Code Playgroud)
来自https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#cast
cat*_*ran 12
使用queryset的extra()方法:
students.objects.filter(student_id__contains="97318") \
.extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \
.order_by('-student_id_uint')
Run Code Online (Sandbox Code Playgroud)
我曾尝试extra()和annotate()给CAST,但他们并没有与相关领域很好地工作,并产生联接有时会造成意想不到的查询集。
我最终是创建一个自定义查找。
这是我的例子:
@Field.register_lookup
class IntegerValue(Transform):
# Register this before you filter things, for example in models.py
lookup_name = 'int' # Used as object.filter(LeftField__int__gte, "777")
bilateral = True # To cast both left and right
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
sql = 'CAST(%s AS UNSIGNED)' % sql
return sql, params
Run Code Online (Sandbox Code Playgroud)
那么下面应该工作:
students.objects.filter(student_id__int__gte="97318").order('-student_id')
Run Code Online (Sandbox Code Playgroud)