Home > Software engineering >  Django filter by empty string or empty string made of spaces
Django filter by empty string or empty string made of spaces

Time:06-08

I would like to filter by a given name that is either an empty string or a string of only blank spaces

For example, I have these names

name1 = ''
name2 = '  '
name3 = '     '
name4 = 'john door'

I would like the query to return all values without characters but made of only spaces which in this case name 1, 2 and 3

Here is my initial attempt but I think it can be made more accurate.

missing_names = Loan.objects.filter(
    Q(Q(name__startswith=' ') & Q(name__endswith=' ')) | Q(name__exact='')
)

CodePudding user response:

You can use the Trim database function to remove all the leading and trailing spaces and then filter on that:

from django.db.models.functions import Trim


missing_names = Loan.objects.annotate(trimmed_name=Trim('name')).filter(trimmed_name='')

With Django 3.2 you can use alias [Django docs] instead of annotate:

from django.db.models.functions import Trim


missing_names = Loan.objects.alias(trimmed_name=Trim('name')).filter(trimmed_name='')

CodePudding user response:

As for the problem you can use the regex operator the Django ORM provides

e.g.

missing_names = Loan.objects.filter(name__regex=r'/^\s*$/')
  • Related