About Using Regular Expressions in Django Querysets
You can capture regular expressions within strings using this technique:
from django.db import models
from people.models import Person
qs = Person.objects.annotate(
twitter_username=models.Func(
models.Func(
models.F("name"),
models.Value(r"\@\S+"),
function="REGEXP_MATCH",
),
models.Value(""),
function="ARRAY_TO_STRING",
)
)
Then in the template you can read the twitter_username
as follows:
{{ person.twitter_username|default:"" }}
Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL Regular Expressions
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.