我有一个用于许多子类的基类,子类中唯一改变的是某种方法(模板模式)。但是我被困住了,无法让它工作。
class Base(models.Model):
_value = models.CharField(max_length=200)
_name = models.CharField(max_length=200)
user = models.ForeignKey(User, related_name="some_set")
#used as a property
def value():
def fget(self):
self.refresh()
return self._value
def refresh(self):
raise NotImplementedError("..")
class Subclass1(Base):
def refresh(self):
self._value = some_val
class Subclass2(Base):
def refresh(self):
self._value = some_other_val
我希望能够将整个相关集视为同一实体,并调用每个实体的 value 属性,每个实体都遵循其自己实现的刷新版本,即
for x in user.some_set.all():
print x.value
但在这一点上,即使删除父类(super class)中的刷新,这似乎也是不可能的。我还考虑过使用策略模式并使用外键关系来调用该方法,但我仍然必须在子类派生的外键中拥有一个基类。
最佳答案
来自文档
Sometimes, however, you only want to change the Python behavior of a model – perhaps to change the default manager, or add a new method.
This is what proxy model inheritance is for: creating a proxy for the original model. You can create, delete and update instances of the proxy model and all the data will be saved as if you were using the original (non-proxied) model. The difference is that you can change things like the default model ordering or the default manager in the proxy, without having to alter the original.
关于python - 有什么方法可以使用 Django 模型作为接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515256/