Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Lookup by length of text field

Tags:

python

sql

django

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 ''?

like image 853
Ram Rachum Avatar asked Mar 29 '13 17:03

Ram Rachum


2 Answers

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

like image 105
var211 Avatar answered Oct 13 '22 09:10

var211


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)
like image 38
jonny Avatar answered Oct 13 '22 08:10

jonny