我們可以在抽象模型上應用索引,以便所有的孩子都繼承它嗎?
我有一個提供其他模型的抽象模型:
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.
在這種模型上進行元繼承的最佳方法是什么?
uj5u.com熱心網友回復:
每個索引必須有一個唯一的名稱;由于子級從父級繼承索引名稱,因此會發生沖突,因此'%(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://www.uj5u.com/ruanti/498008.html
標籤:django
上一篇:如何在django中創建子域?
