Home > Mobile >  Indexing first n characters of Charfield in Django
Indexing first n characters of Charfield in Django

Time:07-15

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));

CodePudding user response:

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')
       ]
  • Related