Django 为继承模型申请迁移

Django apply migrate for inherit models

我有一个基本模型 BaseStage 和两个继承模型 TestSpend 和 StageSpend

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

class TestSpend(BaseStage):
    direction = models.CharField


class StageSpend(BaseStage):
    direction = models.CharField

现在我尝试将约束字段添加到 Meta

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

两个模型。成功 运行ning makemigrations 命令,但是当 运行 migarte 得到

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

试试这个:

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)

根据您的需要替换各种 max_length 值。请注意,现在 direction 字段在各个子类中的实现始终相同,因此您可以使用一个独特的模型,也许带有描述阶段类型的选择字段。