Learner_Programmer Learner_Programmer - 8 months ago 46
MySQL Question

How do i cast char to integer while querying in django ORM?

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;

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

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.


Use queryset's extra() method:

students.objects.filter(student_id__contains="97318") \
                .extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \