1

This might sound like a duplicate, but I don't think it is.

I need to do something a bit similar to what the asker did there : django model polymorphism with proxy inheritance

My parent needs to implement a set of methods, let's call them MethodA(), MethodB(). These methods will never be used directly, they will always be called through child models (but no, abstract class is not the way to go for various reasons).

But this is where it becomes trickier :

Each child model inherits from a specific module (moduleA, moduleB), they all implement the same method names but do something different. The calls are made through the parent model, and are redirected to the childs depending on the values of a field

Since I guess it's not very clear, here is some pseudo-code to help you understand

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

In ModuleA :

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

    def some_other_method():
      #other stuff

In ModuleB :

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

    def some_other_method():
      #other stuff

Right now, the problem is that the class change works, but it does not inherit from ChildModelA or B.

Is this even possible? If yes, how can I make it work, and if no, how could I do this elegantly, without too much repetition?

Community
  • 1
  • 1
Log In
  • 13
  • 4

1 Answers1

0

A proxy model must inherit from exactly one non-abstract model class. It seems that both CustomClass and ParentModel are non-abstract. I would suggest to make CustomClass abstract since no attributes are defined. This is explained in dept here: https://docs.djangoproject.com/en/3.2/topics/db/models/#proxy-models

JLeno46
  • 1,186
  • 2
  • 14
  • 29