9π
OK, I managed to create the indexes using Meta.index_together
. It is not the cleanest way, since I am not actually indexing multiple fields together but it works with makemigrations
:
class Person(models.Model):
class Meta():
index_together = [['last_name']]
first_name = models.CharField()
last_name = models.CharField()
Now makemigrations
does make a new migration:
./manage.py makemigrations app-name
>>Migrations for 'app-name':
>> 0005_auto_20140929_1540.py:
>> - Alter index_together for Person (1 constraint(s))
And the corresponding sql command is actually CREATE INDEX
.
./manage.py sqlmigrate app-name 0005_auto_20140929_1540
>>BEGIN;
>>CREATE INDEX app-name_person_last_name_7...4_idx ON `app-name_person` (`last_name`);
>>COMMIT;
24π
This problem still exists in django2.1.
I solved it by using the indexes Meta option. This is a bit cleaner than the index_together
solution.
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
class Meta:
indexes = [
models.Index(fields=['last_name']),
]
- [Django]-Django staticfiles app help
- [Django]-Django : Filter query based on custom function
- [Django]-Request.data in DRF vs request.body in Django
9π
You can do this explicitly in your migration using Djangoβs AddIndex and Index classes.
First create an empty migration with manage.py makemigrations --empty
and then simply fill it out as follows:
from django.db import migrations
from django.db.models.indexes import Index
from django.db.migrations import AddIndex
class Migration(migrations.Migration):
dependencies = [
('app_name', 'ref_to_previous_migration'),
]
operations = [
AddIndex('ModelName', Index(fields=['field_name'], name='my_index'))
]
You can use options on the Index
class to specify fields, add a name, and do special custom things like index only part of the table, etc. Check the doc links above.
- [Django]-Django 1.7 β How do I suppress "(1_6.W001) Some project unittests may not execute as expected."?
- [Django]-How to write a Pandas DataFrame to Django model
- [Django]-For Django models, is there a shortcut for seeing if a record exists?