Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert string to int before quering 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading