我有一个 Django 模型:
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)
我希望当 inherit
不是 null/blank 时,attribute1 和 attribute2 等是从父对象 inherit
继承的,这样当我访问属性时我得到了 parent 的值(value)观。我不关心为 child 设定值(value)观。
我考虑过使用模型方法,例如:
_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)
但它看起来很难看,因为我有大约 10 个属性。有更好的方法吗?
最佳答案
也许 __getattr__
和 __setattr__
是一个不错的选择。
class Foo(models.Model):
name = models.CharField(unique=True)
inherit = models.ForeignKey('self', related_name='children', null=True, blank=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)
def __getattr__(self, name):
if self.inherit and hasattr(self.inherit, name):
return getattr(self.inherit, name, None)
elif hasattr(self, '_'+name):
return getattr(self, '_'+name, None)
return super(Foo, self).__getattr__(name)
def __setattr__(self, name, value):
if self.inherit and hasattr(self.inherit, name):
return setattr(self.inherit, name, value)
elif hasattr(self, '_'+name):
return self.__dict__[name] = value
return super(Foo, self).__setattr__(name, value)
免责声明:我没有尝试运行这个
关于python - 在Django中继承外键->'self'关系中的特定父模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1824667/