[Fixed]-Django: Lookup by length of text field

18👍

I think regex lookup can help you:

ModelWithTextField.objects.filter(text_field__iregex=r'^.{7,}$')

or you can always perform raw SQL queries on Django model:

ModelWithTextField.objects.raw('SELECT * FROM model_with_text_field WHERE LEN_FUNC_NAME(text_field) > 7')

where len_func_name is the name of “string length” function for your DBMS. For example in mysql it’s named “length”.

👤var211

12👍

Since django 1.8, you can use the Length database function:

from django.db.models.functions import Length
qs = ModelWithTextField.objects \
        .annotate(text_len=Length('text_field_name')) \
        .filter(text_len__gte=7)
👤jonny

3👍

Since Django 1.9 the Length database function may be registered as a queryset lookup:

from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length, 'length')

So that then you are able use it in a following manner:

# Get authors whose name is longer than 7 characters
authors = Author.objects.filter(name__length__gt=7)

See: Database Functions – Length() in official Django 3.2 Docs

Leave a comment