【发布时间】:2016-11-06 15:05:50
【问题描述】:
我有一个做得太多的 Django 模型。这是该模型的缩写示例。基本上,它可以表示四种不同的Entity 类型,并且存在指向其他实体的递归ForeignKey 和ManyToMany 关系。
这个项目目前使用的是 Django 1.8.x 和 Python 2.7.x,但如果解决方案需要,我可以升级它们。
class Entity(models.Model):
"""
Films, People, Companies, Terms & Techniques
"""
class Meta:
ordering = ['name']
verbose_name_plural = 'entities'
# Types:
FILM = 'FILM'
PERSON = 'PERS'
COMPANY = 'COMP'
TERM = 'TERM'
TYPE_CHOICES = (
(FILM, 'Film'),
(PERSON, 'Person'),
(COMPANY, 'Company'),
(TERM, 'Term/Technique'),
)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
type = models.CharField(max_length=4, choices=TYPE_CHOICES, default=FILM)
slug = models.SlugField(blank=True, unique=True, help_text="Automatically generated")
name = models.CharField(max_length=256, blank=True)
redirect = models.ForeignKey('Entity', related_name='entity_redirect', blank=True, null=True, help_text="If this is an alias (see), set Redirect to the primary entry.")
cross_references = models.ManyToManyField('Entity', related_name='entity_cross_reference', blank=True, help_text="This is a 'see also' — 'see' should be performed with a redirect.")
[... and more fields, some of them type-specific]
我意识到这相当混乱,我想删除“类型”并创建一个 EntityBase 类来抽象出所有公共字段,并创建新的 Film、Person、Company ,以及继承自 EntityBase 抽象基类的 Term 模型。
创建新模型后,我想我了解如何编写数据迁移以将所有字段数据移至新模型(从Entity 迭代对象,通过type 过滤,创建新对象在适当的新模型中)... 除了 ForeignKey 和 ManyToMany 关系。也许我想错了,但是在迁移过程中,如果关系指向的新对象可能还不存在,我该如何转移这些关系呢?
我怀疑这可能意味着多步骤迁移,但我还没有找到正确的方法。
【问题讨论】:
-
再想一想之后,我意识到我有the same problem as this fellow。我想知道是否按照我上面的建议来增加模型的概念清晰度,只会在关系和视图方面给我带来更多麻烦。要么我现在必须查询 4+ 模型才能得出所有“相关”结果,要么我必须摆弄像
django-gm2m这样的东西。 -
切换到具体继承(而不是抽象继承)似乎可以解决 那些 问题,但是 Django 社区的知名成员有 dire warnings about using concrete inheritance,所以……也许我应该保持原样,并清理我的管理代码以隐藏每种类型的不必要字段吗?
标签: django django-models django-migrations