相关疑难解决方法(0)

Django多表继承,如何知道哪个是模型的子类?

我在django中遇到多表继承问题.

让我们以银行账户为例.

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

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
Run Code Online (Sandbox Code Playgroud)

现在,我想为帐户类型添加一个值,但我拥有的只是一个帐户对象,例如acc = account.object.get(pk = 29).那么,谁是acc的孩子?

Django会自动在accounttypeA和accounttypeB中创建account_ptr_id字段.所以,我的解决方案是:

child_class_list = ['accounttypeA', 'accounttypeB']

for cl in child_class_list:
    try:
        exec(“child = ” + str(cl) + “.objects.select_for_update().get(account_ptr_id=” +              str(acc.id) + “)”)
        logger.debug(“Child found and ready to use.”)
        return child
    except ObjectDoesNotExist:
        logger.debug(“Object does not exist, moving on…”) …
Run Code Online (Sandbox Code Playgroud)

python django inheritance subclass

13
推荐指数
2
解决办法
4950
查看次数

标签 统计

django ×1

inheritance ×1

python ×1

subclass ×1