Python 3.x 在AbstractClass的字段上添加索引
我创建了一个提供默认时间戳的抽象模型,我想在该模型中声明的字段上创建索引 父模型Python 3.x 在AbstractClass的字段上添加索引,python-3.x,django,django-models,django-rest-framework,Python 3.x,Django,Django Models,Django Rest Framework,我创建了一个提供默认时间戳的抽象模型,我想在该模型中声明的字段上创建索引 父模型 class CommonModel(models.Model): """ Provides default timestamp model """ updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeFiel
class CommonModel(models.Model):
"""
Provides default timestamp model
"""
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class User(CommonModel):
name = models.CharField(max_length=128, blank=False, null=False)
work_email = models.CharField(max_length=128, blank=False, null=False)
phone = models.CharField(max_length=20, blank=False, null=False)
class Meta:
db_table = 'user'
子模型
class CommonModel(models.Model):
"""
Provides default timestamp model
"""
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class User(CommonModel):
name = models.CharField(max_length=128, blank=False, null=False)
work_email = models.CharField(max_length=128, blank=False, null=False)
phone = models.CharField(max_length=20, blank=False, null=False)
class Meta:
db_table = 'user'
我想在创建的_at字段上应用索引
注:我正在使用django==2.0.5、djangorestframework==3.8.2、Python3.6.5您可以使用
Meta
类中的属性(在django==1.11中引入,因此它将适用于您)设置索引:
class EBUser(CommonModel):
name = models.CharField(max_length=128, blank=False, null=False)
work_email = models.CharField(max_length=128, blank=False, null=False)
phone = models.CharField(max_length=20, blank=False, null=False)
class Meta:
db_table = 'user'
indexes = [
models.Index(fields=['created_at'], name='created_at_idx'),
]
声明索引后,生成的迁移列在下面,出于某种原因,它没有提到项目类迁移(migrations.migration)中的所有模型:operations=[migrations.AddIndex(model_name='',index=models.index(fields=['created_at'],name='created_at_idx'),]@aMighty您可能已经在以前的迁移文件中创建了其他模型。它不应该有针对的更改吗indexes@aMighty当您在此模型上设置索引时,为什么其他模型会更改?注意:在
EBUser
上设置索引并不意味着在继承自CommonModel
的所有模型上设置索引。如果要这样做,请在CommonModel
的Meta
中创建索引,并让其他模型Meta
继承它。