Например:
Код: Выделить всё
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
Код: Выделить всё
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)
Код: Выделить всё
field_list = name.split(LOOKUP_SEP)
^^^^^^^^^^
AttributeError: 'Col' object has no attribute 'split'
Подробнее здесь: https://stackoverflow.com/questions/787 ... ther-int-o