Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int before querying django ORM

Tags:

python

django

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

like image 232
maca2.0 Avatar asked Oct 15 '25 21:10

maca2.0


1 Answers

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)
like image 184
Alain Bianchini Avatar answered Oct 18 '25 11:10

Alain Bianchini