【问题标题】:Django model polymorphism, using proxy inheritanceDjango模型多态,使用代理继承
【发布时间】:2013-04-08 17:11:22
【问题描述】:

这听起来像是重复的,但我认为不是。

我需要做一些类似于提问者在那里所做的事情:django model polymorphism with proxy inheritance

我的父母需要实现一组方法,我们称它们为 MethodA()、MethodB()。这些方法永远不会被直接使用,它们总是会通过子模型被调用(但是不,由于各种原因,抽象类不是要走的路)。

但这就是它变得更棘手的地方:

每个子模型都继承自一个特定的模块(模块A、模块B),它们都实现了相同的方法名称,但做的事情不同。调用是通过父模型进行的,并根据字段的值重定向到子模型

由于我猜的不是很清楚,这里有一些伪代码帮助你理解

from ModuleA import CustomClassA
from ModuleB import CustomClassB

class ParentModel(models.Model):

TYPE_CHOICES = (
  ('ChildModelA', 'A'),
  ('ChildModelB', 'B'),
)

    #some fields
    type = models.CharField(max_length=1, choices=TYPE_CHOICES)
    def __init__(self, *args, **kwargs):
        super(ParentModel, self).__init__(*args, **kwargs)
        if self.type:
          self.__class__ = getattr(sys.modules[__name__], self.type)

    def MethodA():
      some_method()

    def MethodB():
      some_other_method()

class ChildModelA(ParentModel, CustomClassA):
    class Meta:
      proxy = True

class ChildModelB(ParentModel, CustomClassB):
    class Meta:
      proxy = True

在模块 A 中:

class CustomClassA():
    def some_method():
      #stuff

    def some_other_method():
      #other stuff

在模块 B 中:

class CustomClassB():
    def some_method():
      #stuff

    def some_other_method():
      #other stuff

现在,问题是类更改有效,但它没有从 ChildModelA 或 B 继承。

这甚至可能吗?如果是,我怎样才能让它工作,如果不是,我怎么能优雅地做到这一点,没有太多重复?

【问题讨论】:

    标签: python django django-models polymorphism proxy-classes


    【解决方案1】:

    代理模型必须仅继承自一个非抽象模型类。似乎CustomClassParentModel 都不是抽象的。我建议将CustomClass 设为抽象,因为没有定义任何属性。 这在此处详细解释:https://docs.djangoproject.com/en/3.2/topics/db/models/#proxy-models

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多