Django多表继承,怎么知道哪个是子类的一个模型? [英] Django multi-table inheritance, how to know which is the child class of a model?
问题描述
让我们举个例子来看一下银行帐户。
model.Model):
name = models ...
class accounttypeA(account):
balance = models.float ... ..
def addToBalance (self,value):
self.balance + = value
class accounttypeB(account):
balance = models.int ... #注意这个
def addToBalance(self,value):
value = do_some_thing_with_value(value)#注意这个
self.balance + = value
现在,我想为一个accounttype添加一个值,但是我所有的都是一个帐户对象,例如acc = account.object。 get(pk = 29)。所以,谁是孩子的孩子?
Django会自动在accounttypeA和accounttypeB中创建一个account_ptr_id字段。所以我的解决方案是:
child_class_list = ['accounttypeA','accounttypeB']
cb in child_class_list:
try:
exec(child =+ str(cl)+.objects.select_for_update()。get(account_ptr_id =+ str(acc.id)+ )
logger.debug(找到并准备使用的子项)
返回child
除了ObjectDoesNotExist:
logger.debug(Object does not exist,moving on ... )
也许这是一个绘图板问题在这一点上! :)
我希望在我的例子中已经清楚了。感谢
据我所知,Django内置的方式并没有这样做。
但是,给定 acc = account.object.get(pk = 29)
,可以使用:
try:
typeA = acc.accounttypeA
#acc是typeA
除了accounttypeA.DoesNotExist:
#acc应该是typeB,如果帐户只有typeA和typeB子类
try:
typeB = acc.accounttypeB
#acc是typeB
,除了accounttypeB.DoesNotExist:
#acc应该是typeA,如果帐户只有typeA和typeB子类
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……
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
Now, i want to add a value to an accounttype, but all i have is an account object, for instance acc=account.object.get(pk=29) . So, who is the child of acc ?
Django automatically creates an account_ptr_id field in accounttypeA and accounttypeB. So, my solution was:
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…")
Maybe it's a drawing board problem at this point! :)
I hope I have been clear in my example. Thanks
To the best of my knowledge there isn't a Django built-in way to do this.
However, given acc=account.object.get(pk=29)
, you can use:
try:
typeA = acc.accounttypeA
# acc is typeA
except accounttypeA.DoesNotExist:
# acc should be typeB if account only has typeA and typeB subclasses
try:
typeB = acc.accounttypeB
# acc is typeB
except accounttypeB.DoesNotExist:
# acc should be typeA if account only has typeA and typeB subclasses
这篇关于Django多表继承,怎么知道哪个是子类的一个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!