Msv
Msv

Reputation: 1371

Indexing first n characters of Charfield in Django

How to index a specific number of Characters on Django Charfield?

For example, this is how we index fields in Django, but I guess it applies to entire field or all characters.

class Meta:
       indexes = [
           models.Index(fields=['last_name', 'first_name',]),
           models.Index(fields=['-date_of_birth',]),
]

So, how to apply index to specific portion of field as shown in mysql below.

CREATE INDEX part_of_name ON customer (name(10));

Upvotes: 3

Views: 545

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

You can create a functional index with the Substr function [Django-doc]:

from django.db.models.functions import Substr

# …

class Meta:
       indexes = [
           models.Index(fields=['last_name', 'first_name']),
           models.Index(fields=['-date_of_birth']),
           models.Index(Substr('pub_date', 0, 10), name='part_of_name')
       ]

Upvotes: 5

Related Questions