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

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.