更改Django模型实例的多态内容类型 [英] Change the polymorphic content type of a django model instance

查看:77
本文介绍了更改Django模型实例的多态内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个多态模型:

If I have a polymorphic model:

class Father(polymorphic.model.PolymorphicModel)

和没有额外字段的继承类:

and an inheritor class with no extra fields:

class Child(Father)

当我有父亲的实例时,我该如何

When I have an instance of Father, how can I convert it to a Child instance?

我尝试过的是:

foo = Father.objects.get(pk=1)
# foo is just a Father, no record in Child database table.
foo.polymorphic_ctype = ContentType.objects.get(app_label='myapp', model='child')
foo.save()

但没有任何变化。我希望 foo 成为子对象,并且需要将此对象放入子数据库表中。

But nothing changes. I want foo to be a Child object and need to have this into the child database table.

推荐答案

确定。

在阅读了类似的帖子之后,我意识到我需要另一项作业:

After reading this similar post I realized that I needed another assignment:

foo.__class__ = Child

这将在子表中进行插入,否则永远不会发生。

This makes an insertion in the child table otherwise never happened.

这篇关于更改Django模型实例的多态内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆