Django model subclassing: Get the subclass by querying the superclass

后端 未结 4 1615
渐次进展
渐次进展 2020-12-16 23:01

The following code is given:

class BaseMedium(models.Model):
    title = models.CharField(max_length=40)
    slug = models.SlugField()

class A(BaseMedium):
         


        
4条回答
  •  -上瘾入骨i
    2020-12-16 23:35

    The only way to do this is to explicitly store on the base model what type it is. So have a derived_type (or whatever) field on BaseMedium, and set it on save. Then you can have a get_derived_type method:

    def get_derived_type(self):
        if self.derived_type ==  'A':
            return self.a
        elif self.derived_type == 'B':
            return self.b
    

    and so on.

提交回复
热议问题