I’m trying to create a custom django lookup as_int
so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong format.
For example:
<code>Comment.objects.filter(body__as_int__gt=5)
# Should treat a comment with body="37" as 37
# Should treat a comment with body="abc" as NULL
</code>
<code>Comment.objects.filter(body__as_int__gt=5)
# Should treat a comment with body="37" as 37
# Should treat a comment with body="abc" as NULL
</code>
Comment.objects.filter(body__as_int__gt=5)
# Should treat a comment with body="37" as 37
# Should treat a comment with body="abc" as NULL
This is what I have so far:
<code>class AsIntTransform(Transform):
lookup_name = "as_int"
output_field = models.IntegerField()
def as_sql(self, compiler, connection):
case_expr = Case(
When(
Regex(self.lhs, r"^d+$"),
then=Cast(self.lhs, models.IntegerField()),
),
default=Value(None),
)
return case_expr.as_sql(compiler, connection)
models.CharField.register_lookup(AsIntTransform)
models.TextField.register_lookup(AsIntTransform)
</code>
<code>class AsIntTransform(Transform):
lookup_name = "as_int"
output_field = models.IntegerField()
def as_sql(self, compiler, connection):
case_expr = Case(
When(
Regex(self.lhs, r"^d+$"),
then=Cast(self.lhs, models.IntegerField()),
),
default=Value(None),
)
return case_expr.as_sql(compiler, connection)
models.CharField.register_lookup(AsIntTransform)
models.TextField.register_lookup(AsIntTransform)
</code>
class AsIntTransform(Transform):
lookup_name = "as_int"
output_field = models.IntegerField()
def as_sql(self, compiler, connection):
case_expr = Case(
When(
Regex(self.lhs, r"^d+$"),
then=Cast(self.lhs, models.IntegerField()),
),
default=Value(None),
)
return case_expr.as_sql(compiler, connection)
models.CharField.register_lookup(AsIntTransform)
models.TextField.register_lookup(AsIntTransform)
Trying to filter with the above code is throwing:
<code> field_list = name.split(LOOKUP_SEP)
^^^^^^^^^^
AttributeError: 'Col' object has no attribute 'split'
</code>
<code> field_list = name.split(LOOKUP_SEP)
^^^^^^^^^^
AttributeError: 'Col' object has no attribute 'split'
</code>
field_list = name.split(LOOKUP_SEP)
^^^^^^^^^^
AttributeError: 'Col' object has no attribute 'split'
It looks like the ‘Col’ its referring to here is self.lhs
in the transform, but I’m not sure what I’m supposed to change to make this work?