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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With