Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 717
Msv Avatar asked Nov 27 '25 18:11

Msv


1 Answers

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')
       ]
like image 113
Willem Van Onsem Avatar answered Nov 30 '25 09:11

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!