Django OneToOneField to multiple models

天大地大妈咪最大 提交于 2019-12-05 16:55:37
utapyngo

https://stackoverflow.com/a/23547494/517316

Instead of putting the relation to RelatedModel, it is possible to put it to Submodel1 .. Submodel9.

class Submodel1(models.Model):
    some_field = models.TextField()
    related_model = models.OneToOneField(RelatedModel, 
                                         null=True, blank=True, 
                                         related_name='the_thing')

...

class Submodel9(models.Model):
    another_field = models.TextField()
    related_model = models.OneToOneField(RelatedModel,
                                         null=True, blank=True,
                                         related_name='the_thing')

Or, if we make BaseModel abstract, we can define it right in BaseModel:

class BaseModel(models.Model)
    related_model = models.OneToOneField(RelatedModel, 
                                         null=True, blank=True,
                                         related_name='the_thing')

    class Meta:
        abstract = True

This would allow accessing SubmodelX from an instance of RelatedModel using a field named the_thing, just as in the multi-table inheritance example.

It is possible to achieve with 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!