django - 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
解决方案
尝试这个:
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
各个子类中字段的实现始终相同,因此您可以使用一个独特的模型,也许可以使用描述阶段类型的选择字段。
推荐阅读
- c# - 在 WPF 中,将 ViewModel 中的 UserControl C# 对象添加到 View
- solr - Classic Tokenizer 未按预期工作
- azure - AKS:如何摆脱负载均衡器?
- django - 如何从数组列表字段中过滤整数列表
- html - 如何使用本地文件 svg?
- azure-devops - Azure Devops YAML 管道中的条件依赖作业
- python - 我解析 Beautifulsoup 时没有文本
- python - 如何获取导入的python文件的绝对路径
- uwp - VS2017:构建 store 包时,bundle.upload 文件不会被创建
- excel - 条件格式问题 - Excel (AND,ISNUMBER,LARGE)