Search code examples
djangodjango-migrations

Django apply migrate for inherit models


I have a base model BaseStage and two inherit models TestSpend , StageSpend

class BaseStage(models.Model):
    name = models.CharField
    date = models.DateField
.......

class TestSpend(BaseStage):
    direction = models.CharField


class StageSpend(BaseStage):
    direction = models.CharField

Now Im try to add constraints field to Meta

class Meta:
    verbose_name = ''
    verbose_name_plural = ''
    constraints = [
         models.UniqueConstraint(
             fields=['direction', 'name', 'date'], name='unique_name'
         )
     ]

to both models. Successfully running the makemigrations command, but when run migarte got

django.db.utils.ProgrammingError: column "name" named in key does not exist

Solution

  • Try this:

    class BaseStage(models.Model):
        name = models.CharField(max_length=30)
        date = models.DateField()
        # Other fields
        
        @property
        def direction(self):
            raise NotImplemented
       
        class Meta:
            abstract = True
            constraints = [UniqueConstraint(name='%(class)s_unique_name', fields=['direction', 'name', 'date'])]
    
    class TestSpend(BaseStage):
        direction = models.CharField(max_length=30)
    
    
    class StageSpend(BaseStage):
        direction = models.CharField(max_length=30)
    

    Replace the various max_length values with your needs. Note that right now the implementation of the direction field in the various subclasses is always the same, so you could use one unique model maybe with a choice field that describes the type of stage.