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

前端 未结 4 2161
梦毁少年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条回答
  •  猫巷女王i
    2021-02-19 04:06

    Django adds to class account two fields: accounttypea and accounttypeb. If you have accounttypeB object with pk=42, you can access from parent like this:

    account.objects.get(pk=42).accounttypeb
    >>> 
    

    You can add CharField to parent model with actual child-type for every child, and then use getattr, if there are a lot of child models (it may be better than a lot of try .. except xxx.DoesNotExist blocks).

    class account(models.Model):
        name = models……
        cls = CharField(...)  
    
        def ext(self):
            return getattr(self, self.cls.lower())
    
    
    class accounttypeA(account):
        balance = models.float…..
    
        def addToBalance(self, value):
            self.balance += value
    
    
    class accounttypeB(account):
        balance = models.int…. # NOTE this
    
        def addToBalance(self, value):
            value = do_some_thing_with_value(value) # NOTE this
            self.balance += value
    
    # example
    accounttypeB.objects.create(balance=10,  name='Vincent Law', cls="accounttypeB")  
    accounttypeA.objects.create(balance=9.5, name='Re-l Mayer', cls="accounttypeA")  
    for obj in account.objects.all():
        obj.ext().addToBalance(1.0) 
        print(obj.name, obj.cls)
    

    but you MUST create models using accounttypeA.objects.create(...) and accounttypeB.objects.create(...) - or else this trick will not work. (https://docs.djangoproject.com/en/1.5/topics/db/models/#multi-table-inheritance)

提交回复
热议问题