Home > Enterprise >  Django query number of occurences of a character in CharField
Django query number of occurences of a character in CharField

Time:12-16

I have a CharField who contains paths, like: zero/one/two/three , or root/usr/et_cetera

The number of separators (here /) give us the depth of the 'node' in the path, so on the previous example, three has a depth of 3.

In python, I could write 'zero/one/two'.count('/'), but I wonder how to do it in a Django query.

What I search is something like following:

# Hypothetical code, does not work
Model.object.annotate(depth=CountChr('path', V('/'))).filter(depth=2)

I can't find a function who does that in the django documentation.

CodePudding user response:

This should be possible by replacing all occurrences of the char we are looking for with a blank string, finding the length with the chars replaced and subtracting it from the original length

from django.db.models.functions import Replace, Length

Model.object.annotate(depth=Length('path') - Length(Replace('path', Value('/')))).filter(depth=2)

CodePudding user response:

You can use Django regex filter.

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#regex

You can try this or similar to this

Model.object.filter(path__regex=r'\w*\\w{2}')
  • Related