Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django filter on the basis of text length

Tags:

django

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

like image 728
ashish Avatar asked Sep 07 '12 08:09

ashish


People also ask

What does the length filter do Django?

Definition and Usage The length filter returns the number of items in an object.

How do I find the length of a QuerySet?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.

What does .all do in Django?

Definition of the all() manager method: all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.


1 Answers

For Django >= 1.8 you can use the Length function, which is @Pratyush's CHAR_LENGTH() under the hood for MySQL, or LENGTH() for some other databases:

from django.db.models.functions import Length qs = MyModel.objects.annotate(text_len=Length('text_field_name')).filter(     text_len__gt=10) 
like image 134
hobs Avatar answered Jan 04 '23 16:01

hobs