Home > OS >  Django: Applying indexes on abstract models so that children have it
Django: Applying indexes on abstract models so that children have it

Time:07-04

Can we apply indexes on abstract models so that all children inherit it?

I have an abstract model which feeds other models :

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)

And I wanted to add an index on that abstract model so that I have :

    class Meta:
        abstract = True
        indexes = (
            BrinIndex(fields=['created_at']),
            BrinIndex(fields=['updated_at']),
        )   

I have this error:

(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.

What is the best way to do meta inheritance on such model ?

CodePudding user response:

Each index must have a unique name; since children inherit the index name from the parent, a collision occurs, so an explicit name containing '%(class)s' must be set:

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')
      )   

If other models inherit from ModelA, it should be set as abstract. Otherwise make them inherit from TimeStampedUUIDModel and redefine the common fields.

  • Related