uta*_*ngo 5 django model abstract
假设我们有一个基本模型:
class BaseModel(models.Model):
pass
Run Code Online (Sandbox Code Playgroud)
有一些子类:
class Submodel1(BaseModel):
some_field = models.TextField()
...
class Submodel9(BaseModel):
another_field = models.TextField()
Run Code Online (Sandbox Code Playgroud)
每个子模型都在其自己的 Django 应用程序中定义。可以出现带有新子模型的新应用程序。
我们还有另一个模型,我们称之为RelatedModel,它应该与 具有一对一的关系BaseModel:
class RelatedModel(models.Model):
the_thing = models.OneToOneField(BaseModel, null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)
如果 ,是否可以定义这样的关系BaseModel.Meta.abstract == True?或者BaseModel根本没有定义?
我在下面发布了一些解决方案作为答案,但对我来说它们似乎有点难看。
可以使用 GenericForeignKeys 来实现:
class RelatedModel(models.Model):
content_type_of_the_thing = models.ForeignKey(ContentType)
id_of_the_thing = models.PositiveIntegerField()
the_thing = GenericForeignKey('content_type_of_the_thing', 'id_of_the_thing')
class Meta:
unique_together = ('content_type_of_the_thing', 'id_of_the_thing')
# TODO: restrict `content_type_of_the_thing` by `Submodel1 .. Submodel9` somehow
# Take into account that new submodels can appear
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3416 次 |
| 最近记录: |