Understanding Django Model Inheritance
I'm having trouble understanding why some properties exist in some models, so I hope someone can explain them here.
Here's a basic example:
class Alpha(models.Model):
one = models.PositiveIntegerField()
class Bravo(Alpha):
two = models.PositiveIntegerField()
class Charlie(Alpha):
three = models.PositiveIntegerField()
"bravo" in dir(Charlie())
True
How is it that an instance Charlie
has a property bravo
? Is there a reason for this? Did I miss something?
More importantly, why is it stopping me from adding a property bravo
to the class Charlie
?
...
class Charlie(Alpha):
three = models.PositiveIntegerField()
bravo = models.TextField()
Charlie()
ValueError: Cannot assign "''": "Charlie.bravo" must be a "Bravo" instance.
source to share
The inheritance interaction introduces links between the child model and each of its parents (via the automatically generated OneToOneField).
In your case, this means that Bravo Alpha is named "bravo" by definition.
See. Inheriting multiple tables and Inheritance and reverse relations documentation.
source to share
As far as I can tell, this is a consequence of the fact that the parent class has an implicit foreign key for all of its descendants, which in turn is inherited by the children. This probably shouldn't actually happen, but there can be no way to prevent it.
One possibility might be to explicitly set the parent link to Bravo to be related_name
something other than "bravo" so that you can reuse that name in Charlie.
class Bravo(Alpha):
two = models.PositiveIntegerField()
alpha = models.OneToOneField(Alpha, parent_link=True, related_name='not_bravo')
source to share