Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django OneToOneField to multiple models

Suppose we have a base model:

class BaseModel(models.Model):
    pass

with some subclasses:

class Submodel1(BaseModel):
    some_field = models.TextField()

...

class Submodel9(BaseModel):
    another_field = models.TextField()

Each submodel is defined in its own Django app. New apps with new submodels can appear.

We also have another model, let's call it RelatedModel, which should have a one-to-one relation to BaseModel:

class RelatedModel(models.Model):
    the_thing = models.OneToOneField(BaseModel, null=True, blank=True)

Is it possible to do define such a relation if BaseModel.Meta.abstract == True? Or without defining BaseModel at all?

I have posted some solutions as answers below, but they seem a bit ugly to me.

like image 503
utapyngo Avatar asked May 09 '14 01:05

utapyngo


1 Answers

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
like image 139
utapyngo Avatar answered Oct 19 '22 17:10

utapyngo