rcepre
rcepre

Reputation: 313

Django query number of occurences of a character in CharField

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.

Upvotes: 2

Views: 1105

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

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)

Upvotes: 5

rahul.m
rahul.m

Reputation: 5854

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}')

Please try different regex patterns

Upvotes: 1

Related Questions