Home > Database > Mysql Tutorial > body text

How to Cast a CharField to an Integer in Django ORM Queries?

DDD
Release: 2024-11-02 17:55:29
Original
805 people have browsed it

How to Cast a CharField to an Integer in Django ORM Queries?

Casting Char to 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>
Copy after login

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>
Copy after login

The Cast function takes two arguments:

  • The field name to be cast.
  • The data type to cast the field to.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template