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:

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:

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