116

I would like to filter my model on the basis of the length of the text Something like

MyModel.objects.filter(len(text) > 10)

where text is a Char or Text field in MyModel model

1

6 Answers 6

298
+50

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.

5
  • 1
    Say I don't want to filter the queryset, but instead return itself in with the objects text_len__gt=10 in first place (order_by). Any hint?
    – vabada
    Jul 27, 2016 at 9:51
  • 3
    @dabad, you can use the text_len annotation in the same way you would use any other database field, so it works in order_by or Sum or whatever. To sort the results in decreasing text length order and return the length values: MyModel.objects.annotate(text_len=Length('text_field_name')).order_by('-text_len').values_list('text_len', flat=True).
    – hobs
    Aug 4, 2016 at 16:20
  • 1
    @guettli A problem with the accepted answer is, that the original poster has been seen last time in September 2015 at SO and your admirable altruism was the only possibility :-) I had to edit this answer before I could upvote. I added a similar answer for Django >= 1.9 that doesn't require annotate, but a global registration of Length Transform.
    – hynekcer
    Jul 24, 2017 at 14:24
  • 1
    This is very difficult to find in the docs, because it's not grouped with other aggregations like Sum. It's also extremely important for many cases. I had a case where I needed to pre-check the maximum data size that a query might return won't run the server out of memory, and a variant of this worked perfectly.
    – AlanSE
    Dec 16, 2017 at 15:41
  • @AlanSE the reason they didn't document it with Sum and other aggregations is because it's not an aggregation. It works on individual records (rows). The resulting queryset has the same number of rows as before running the Length operator. So it's called a transformation or a mapping. Aggregations reduce the number of records. Mappings do not.
    – hobs
    Dec 24, 2020 at 15:45
66

Another way is:

MyModel.objects.extra(where=["CHAR_LENGTH(text) > 300"])

This can be used where the text lenght is more than 255 characters too.

1
64

A nice solution for Django >= 1.9 is possible by registering the builtin function Length as a Transform for CharField lookup.

Register the transformation in the project once. (The best place is probably models.py.)

from django.db.models import CharField
from django.db.models.functions import Length

CharField.register_lookup(Length, 'length')

Use:

result = MyModel.objects.filter(text__length__gt=10)

See exactly the same example in docs for Length as a transform.


It works correctly for all backends, compiled by LENGTH() for most backends and by CHAR_LENGTH() for MySQL. It is then registered for all subclasses of CharField automatically, e.g. for EmailField. The TextField must be registered individually. It is safe to register the name "length", because a transform name could never shade or be shaded by an equally named field name or related field name.

The only disadvantage could be readability puzzle: Where did the "length" come from? (The lookup is global, but the same can be luckily safely registered repeatedly in more modules, if useful for readability, without any possible overhead at query runtime.)

Other similarly valuable solution is the hobs's above that is shorter if a registration counts and if a similar query is not used repeatedly.

2
  • @guettli Unexpected that you had written a solution first and a minute before you started the bounty? I did it also in a strange order: I found details for the solution from Django source, then found it all is in the docs about finally that you had known the solution first.
    – hynekcer
    Jul 23, 2017 at 2:58
  • I started a bounty since the accepted question, which still is unfortunately still the one on the top, was outdated. I was hoping that the answer with the Length function (>= Django 1.8) was getting more upvotes. AFAIK this happened, but unfortunately the outdated answer is still on the top.
    – guettli
    Jul 24, 2017 at 8:15
34

You can use the regex filter to search for text of a particular length:

MyModel.objects.filter(text__regex = r'.{10}.*')

Caveat: for MySQL, the maximum length value is 255. Otherwise an exception is thrown:

DatabaseError: (1139, "Got error 'invalid repetition count(s)' from regexp")
8
  • 4
    As documentation says: Using raw strings (e.g., r'foo' instead of 'foo') for passing in the regular expression syntax is recommended. Sep 7, 2012 at 9:25
  • I am getting this exception after executing the code OperationalError: (1139, "Got error 'invalid repetition count(s)' from regexp") and this is because of curly braces.
    – ashish
    Sep 7, 2012 at 12:33
  • Actually the exception stated above is basically mysql exception.
    – ashish
    Sep 7, 2012 at 13:33
  • This works fine for any number below 256. MySQL has a maximum repetition count of 256. May 13, 2013 at 12:48
  • 2
    @emil-stenstrom actually, it's 255
    – glarrain
    Jun 4, 2013 at 22:10
-9

I would solve the problem on your app server and not tax your database. You can do this by:

models_less_than_ten = []
mymodel = MyModel.objects.all()
for m in mymodel:
    if len(m.text) > 10:
          models_less_than_ten.append(m)
1
  • 2
    This won't scale well for many rows in MyModel. If you had 100,000 rows, it would be less taxing on the db to do a strlen & decide not to send a row, than sending tons of data to the app server to filter out. It's almost always better to do the work on the db, and if it's too slow or taxing, the query can be optimized.
    – nevelis
    Mar 8, 2018 at 20:13
-21

It would be much better and faster if you just add a column that pre-calculates(memoizes) the length of the text.

e.g.

class MyModel(models.Model):
    text = models.TextField()
    text_len = models.PositiveIntegerField()

     def save(self, *args, **kwargs):
         self.text_len = len(self.text)
         return super(MyModel, self).save(*args, **kwargs)

MyModel.objects.filter(text_len__gt = 10)     # Here text_len is pre-calculated by us on `save`
4
  • Is it because text field isn't indexed and the text length is calculated each time the query hit the database. The solution suggested by lain is doing the same, isn't it (although that solution isn't working for me).
    – ashish
    Oct 8, 2012 at 7:04
  • @ashish 1) Yes it's pre-calculated. 2) No lain doesn't do the same.
    – rantanplan
    Oct 8, 2012 at 8:38
  • 1) So if the length is pre-calculated, then why i need to have another column 2) lain's solution doesn't check for each expression if the character occurence is greater than n ??
    – ashish
    Oct 10, 2012 at 11:45
  • 1
    @ashish I added a comment on the last line of the above code. We add a column to the model to store the length of the text. This is updated everytime the text is modified. So when we query the model, we can filter by the text length, which WE have pre-calculated on our save method.
    – rantanplan
    Oct 10, 2012 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.