Home > Enterprise >  How do I query for "greater than" on a textfield in Django?
How do I query for "greater than" on a textfield in Django?

Time:07-16

I have a certain field in my database which is a textfield. However, for a certain use I have a set of records that only include numbers (saved as a string of course) and I want to query them using "gte" (greater than). Normally I would do:

MyTable.objects.filter(text_field__gte=100)

However, this does not return any results. It seems that I need to cast this field as an integer. Can I do that within this same query? The actual query is more cumbersome and involves external tables (something like MyTable.objects.filter(associated_table__other_table__text_field__gte=100)), but I am simplifying above for clarity.

CodePudding user response:

There is a Cast function that you can use in conjunction with annotating. Hopefully the below will do the trick:

from django.db.models.functions import Cast
from django.db.models import IntegerField
MyTable.objects.annotate(text_int=Cast('text_field', output_field=IntegerField())).filter(text_int__gte=100)
  • Related