在django ORM中查询时如何将char转换为整数? [英] How do i cast char to integer while querying in django ORM?
本文介绍了在django ORM中查询时如何将char转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近开始使用Django ORM.I要执行此查询
Recently started using Django ORM.I want to execute this query
select student_id from students where student_id like "%97318%" order by CAST(student_id as UNSIGNED) desc;
其中student_id是一个CharField,我想要查询的整数。
我尝试使用
where student_id is a CharField which I want as integer for querying. I tried with
students.objects.filter(student_id__contains "97318").order('-student_id')
工作正常。但是不知道如何将student_id转换为int,就像上面提到的Django ORM一样。应该使用原始查询还是有出路?
让我知道你的建议。
works fine. But don't know and couldn't find how to cast "student_id" to int like the actual MySQL query mentioned above with "Django ORM". should I use raw query or is there a way out? Let me know your suggestions.
推荐答案
使用queryset的 extra()方法:
Use queryset's extra() method:
students.objects.filter(student_id__contains="97318") \
.extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \
.order_by('-student_id_uint')
这篇关于在django ORM中查询时如何将char转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文