About Reading a Substring in a Django Queryset

Here's how to read the first and last names from a single name field in a Django queryset with PostgreSQL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.db import models
from django.db.models.functions import Lower
from people.models import Person

qs = Person.objects.annotate(
    first_name=models.Func(
        models.F("name"),
        models.Value(" "),
        models.Value("1"),
        function="SPLIT_PART",
    ),
    last_name=models.Func(
        models.F("name"),
        models.Value(" "),
        models.Value("2"),
        function="SPLIT_PART",
    )
).order_by(Lower("last_name"), Lower("first_name"))

That's analogous to SQL query:

1
2
3
4
SELECT 
  SPLIT_PART(name, ' ', 1) AS first_name, 
  SPLIT_PART(name, ' ', 2) AS last_name, 
...;

Tips and Tricks Programming Development Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL