18👍
✅
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”.
12👍
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)
- Authenticate in Django without a database
- Django mysqlclient install
- How can I grab the API parameter in a Django viewset?
- How to make follower-following system with django model
- Reading file data during form's clean method
3👍
Since Django 1.9 the Length
database function may be registered as a queryset lookup:
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length, 'length')
So that then you are able use it in a following manner:
# Get authors whose name is longer than 7 characters
authors = Author.objects.filter(name__length__gt=7)
See: Database Functions – Length() in official Django 3.2 Docs
- Pass list of fields to QuerySet.values( )
- Django formsets confusion (validation, required, empty_permitted)
Source:stackexchange.com