Django multi-table inheritance, how to know which is the child class of a model?

前端 未结 4 2144
梦毁少年i
梦毁少年i 2021-02-19 03:13

I\'m having a problem with multi-table inheritance in django.

Let’s make an example with bank accounts.

class account(models.Model):
    name = models……         


        
4条回答
  •  醉酒成梦
    2021-02-19 03:59

    my solution was based on this

    class account(models.Model):
        name = models……
    
        def cast(self):
            """
            This method is quite handy, it converts "self" into its correct child class. For example:
    
            .. code-block:: python
    
               class Fruit(models.Model):
                   name = models.CharField()
    
               class Apple(Fruit):
                   pass
    
               fruit = Fruit.objects.get(name='Granny Smith')
               apple = fruit.cast()
    
            :return self: A casted child class of self
            """
            for name in dir(self):
                try:
                    attr = getattr(self, name)
                    if isinstance(attr, self.__class__) and type(attr) != type(self):                 
                        return attr
                except:
                    pass
    
        @staticmethod
        def allPossibleAccountTypes():
            #this returns a list of all the subclasses of account (i.e. accounttypeA, accounttypeB etc)
            return [str(subClass).split('.')[-1][:-2] for subClass in account.__subclasses__()]
    
        def accountType(self):
            try:
                if type(self.cast()) == NoneType:
                    #it is a child
                    return self.__class__.__name__
                else:
                    #it is a parent, i.e. an account
                    return str(type(self.cast())).split('.')[-1][:-2]
            except:
                logger.exception()
        accountType.short_description = "Account type"
    
    class accounttypeA(account):
        balance = models.float…..
    
        def addToBalance(self, value):
            self.balance += value
    
    class accounttypeB(account):
        balance = models.int…. # NOTE this
    

提交回复
热议问题