'Convert string to int before querying django ORM

I have a model

class Entry(models.Model):
    maca = models.CharField(max_length=100, blank=True, null=True)

This field will accept only numbers (cannot set char field to integer field for business reasons)

Now I have to get all entries that have maca greater than 90

What I'm trying to do is this:

Entry.objects.filter(maca__gte=90)

But get isn't working because the maca is a string.

How can I convert maca to int before filtering? Or something like this?

Thanks



Solution 1:[1]

Try this:

from django.db.models.functions import Cast
from django.db.models import IntegerField
Entry.objects.annotate(maca_integer=Cast('maca', output_field=IntegerField())).filter(maca_integer__gte=90)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RedWheelbarrow