Django query number of occurences of a character in CharField

Viewed 206

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.

2 Answers

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
from django.db.models import Value

Model.objects.annotate(depth=Length('path') - Length(Replace('path', Value('/')))).filter(depth__lt=2 + 1)
Related