在Django中建立索引有以下几种技巧:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, db_index=True)
from django.db import models
from django.db.models import Index
class MyModel(models.Model):
my_field = models.CharField(max_length=100)
@property
def my_field_index(self):
return self.my_field
Index('my_field_index', MyModel)
from django.db import models
from django.db.models import Index
class MyModel(models.Model):
my_field = models.CharField(max_length=100)
class MyModelIndex(Index):
fields = ['my_field']
name = 'my_model_my_field_index'
MyModelIndex().create_model(MyModel)
需要注意的是,创建索引可能会对数据库的性能产生影响,因此需要根据具体的需求和数据库负载情况来决定是否创建索引。