I have a Django model:
class Foo(models.Model):
name = models.CharField(unique=True)
attribute1 = models.FloatField(null=True, blank=True)
attribute2 = models.FloatField(null=True, blank=True)
attribute3 = models.BooleanField(null=True, blank=True)
attribute4 = models.CharField(null=True, blank=True)
inherit = models.ForeignKey('self', related_name='children', null=True, blank=True)
I'd like that when inherit
is not null/blank, that attribute1 and attribute2 etc. are inherited from the parent object inherit
so that when I access the attributes I get the values of the parent. I dont care about setting values in the child.
I thought about using model methods eg.:
_attribute1 = models.FloatField(null=True, blank=True)
get_attribute1(self):
if self.inherit:
return self.inherit._attribute1
else:
return self._attribute1
set_attribute1(self, value):
if not self.inherit:
self._attribute1 = value
attribute1 = property(get_attribute1, set_attribute1)
But it seems ugly since I have about 10 attributes. Is there a better way to do this?