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
Definition and Usage The length filter returns the number of items in an object.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With