Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda