Home >Database >Mysql Tutorial >How to Cast a CharField to an Integer in Django ORM Queries?
When querying with Django Object-Relational Mapper (ORM), it might be necessary to cast a character field (CharField) to an integer. This can be achieved using the Cast function, introduced in Django 1.10.
In the given query:
<code class="sql">select student_id from students where student_id like "%97318%" order by CAST(student_id as UNSIGNED) desc;</code>
The student_id field, being a CharField, needs to be cast to an integer (INT) for sorting. To perform this operation in Django ORM, use the following syntax:
<code class="python">from django.db.models import Cast from django.db.models.functions import Cast students.objects.annotate( student_id_int=Cast('student_id', 'INT') # Casting CharField to integer ).order_by('-student_id_int')</code>
The Cast function takes two arguments:
In this example, we cast the student_id field to INT, effectively converting it to an integer for the sorting operation. This allows for accurate sorting of the results using the order_by clause.
The above is the detailed content of How to Cast a CharField to an Integer in Django ORM Queries?. For more information, please follow other related articles on the PHP Chinese website!