Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!