django filter on the basis of text length

For modern Django (>=1.9) @hynecker‘s answer is better.

For Django >= 1.8 you can use an annotation and the Length function:

from django.db.models.functions import Length
qs = MyModel.objects.annotate(text_len=Length('text_field_name')).filter(
    text_len__gt=10)

Under the hood, Django uses is @Pratyush’s suggested CHAR_LENGTH() MariaDB (MySQL) function. But the Django Length function will work for any Django-compatible db by using LENGTH() for Postgres and other databases.

Leave a Comment