Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-11-03 12:34:30
Original
1047 people have browsed it

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

Casting Char to Integer in Django ORM Queries

In Django ORM, you may encounter scenarios where you need to convert a CharField to an integer for querying purposes. Let's explore the options available:

Original Query:

<code class="mysql">select student_id from students where student_id like "%97318%" order by CAST(student_id as UNSIGNED) desc;</code>
Copy after login

Standard Query:

<code class="python">students.objects.filter(student_id__contains="97318").order_by('-student_id')</code>
Copy after login

This query lacks the casting functionality of the MySQL query, resulting in a mismatch.

Using the Cast Function:

From Django 1.10 onward, the Cast function enables casting of fields to various data types. In this case, you can use:

<code class="python">from django.db.models import FloatField
from django.db.models.functions import Cast

students.objects.annotate(student_id_int=Cast('student_id', FloatField()))\
    .filter(student_id__contains="97318").order_by('-student_id_int')</code>
Copy after login

Raw Query:

As an alternative, you can utilize a raw query to achieve the casting:

<code class="python">from django.db import connection

cursor = connection.cursor()
cursor.execute("""
    SELECT student_id
    FROM students
    WHERE student_id LIKE '%%97318%%'
    ORDER BY CAST(student_id AS UNSIGNED) DESC
""")
student_ids = cursor.fetchall()</code>
Copy after login

The above is the detailed content of How to Convert 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template