Ram Rachum
Ram Rachum

Reputation: 88578

Django: Lookup by length of text field

I have a model with a text field on it. I want to do a lookup that will return all the items that have a string with a length of 7 or more in that field. Possible?

How about a lookup for all objects in which that field isn't ''?

Upvotes: 14

Views: 5830

Answers (3)

Krzysiek
Krzysiek

Reputation: 8375

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

Upvotes: 4

jonny
jonny

Reputation: 4673

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)

Upvotes: 14

var211
var211

Reputation: 606

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".

Upvotes: 18

Related Questions