Home > Blockchain >  Convert string to int before quering django ORM
Convert string to int before quering django ORM

Time:04-07

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 gte isn't working because the maca is string

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

Thanks

CodePudding user response:

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)
  • Related