python - 有什么方法可以使用 Django 模型作为接口(interface)吗?

标签 python django python-2.7 design-patterns django-1.6

我有一个用于许多子类的基类,子类中唯一改变的是某种方法(模板模式)。但是我被困住了,无法让它工作。

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)中的刷新,这似乎也是不可能的。我还考虑过使用策略模式并使用外键关系来调用该方法,但我仍然必须在子类派生的外键中拥有一个基类。

最佳答案

使用Proxy Models

来自文档

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/

相关文章:

python - pytest 是否应该从虚拟环境中的依赖模块收集测试?

python - OpenCV Python逐像素循环速度很慢

python - 使用错误凭据的 Django 登录返回 200 而不是 401

python - 我应该如何缩短这行 Python 代码?

python - 如何在不卡住窗口的情况下结合 tkinter 和 wxpython - python?

python - 如何从登录管理员的用户发送电子邮件?

javascript - Ajax请求成功后重定向到单独的Django View

python - 2019 : Dynamic cron jobs Google App Engine

python - 执行从文件中读取的代码

python - 如何刷新 sys.path?