How to filter my model on the basis of text length in django?

0 votes

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

Aug 13 in Python by kartik
• 27,780 points
47 views

1 answer to this question.

0 votes

Hello @kartik,

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)

Hope it helps!!
Thank you!

answered Aug 13 by Niroj
• 59,780 points

Related Questions In Python

0 votes
1 answer

How to extend the User model with custom fields in Django?

Hello @kartik, Define an object manager for your ...READ MORE

answered Aug 3 in Python by Niroj
• 59,780 points
84 views
0 votes
1 answer

How to remove all of the data in a table using Django?

Hello @kartik, Inside a manager: def delete_everything(self): ...READ MORE

answered Aug 12 in Python by Niroj
• 59,780 points
40 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,380 points
261 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29, 2019 in Python by rajesh
• 1,230 points
294 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23 in Python by Niroj
• 59,780 points
192 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23 in Python by Niroj
• 59,780 points
83 views
0 votes
1 answer

How to change the file name of an uploaded file in Django?

Hello @kartik, The basic way is import os os.rename('a.txt', 'b.html') For ...READ MORE

answered Jul 3 in Python by Niroj
• 59,780 points
99 views
0 votes
1 answer