About Using Regular Expressions in Django Querysets

You can capture regular expressions within strings using this technique:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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:

1
{{ person.twitter_username|default:"" }}

Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL Regular Expressions