我们能否将索引应用于抽象模型,以便所有子级都继承它?
我有一个抽象模型,它提供给其他模型:
from model_utils.models import UUIDModel
from django.db import models
class TimeStampedUUIDModel(UUIDModel):
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
class Meta:
abstract = True
class ModelA(TimeStampedUUIDModel):
name_a = models.CharField(max_length=30)
class ModelB(ModelA):
name_b = models.CharField(max_length=30)我想在这个抽象模型上添加一个索引,这样我就有了:
class Meta:
abstract = True
indexes = (
BrinIndex(fields=['created_at']),
BrinIndex(fields=['updated_at']),
) 我有一个错误:
(models.E016) 'indexes' refers to field 'created_at' which is not local to model 'ModelA'.
HINT: This issue may be caused by multi-table inheritance.在这样的模型上做元继承最好的方法是什么?
发布于 2022-07-02 10:14:15
每个索引必须有唯一的名称;由于子索引从父索引继承索引名,因此会发生冲突,因此必须设置包含'%(class)s'的显式名称:
class TimeStampedUUIDModel(UUIDModel):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
indexes = (
BrinIndex(fields=['created_at'], name='%(class)s_created_at_index'),
BrinIndex(fields=['updated_at'], name='%(class)s_updated_at_index')
) 如果其他模型继承自ModelA,则应将其设置为抽象模型。否则,让它们继承TimeStampedUUIDModel并重新定义公共字段。
https://stackoverflow.com/questions/72838171
复制相似问题