首页 > 解决方案 > Django为继承模型申请迁移

问题描述

我有一个基本模型 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'
         )
     ]

两种型号。成功运行makemigrations命令,但运行时migarte得到

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

标签: djangodjango-migrations

解决方案


尝试这个:

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各个子类中字段的实现始终相同,因此您可以使用一个独特的模型,也许可以使用描述阶段类型的选择字段。


推荐阅读