将子类模型实例转换为Django中的另一个子类模型实例? [英] Convert a subclass model instance to another subclass model instance in django?

查看:74
本文介绍了将子类模型实例转换为Django中的另一个子类模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ModelBase和ModelA,ModelB.

I have a ModelBase, and ModelA, ModelB.

我想将ModelA实例更改为ModelB实例. (我可以处理它们具有的属性的差异)

I want to change ModelA instance to ModelB instance. (I can handle the difference of attributes they have)

我看到了相关的问题,但对我而言并不奏效.

I've seen related questions but doesn't quite work for me.

如何如何从现有的基本模型实例创建继承的Django模型实例?
在Django模型上更改子类

  • 编辑

拥有地方-餐馆/酒吧关系后,
我认为能够将餐厅改为酒吧是很合理的.

When you have Place - Restaurant/Bar relationship,
I think it's quite reasonable to be able to switch a restaurant to a bar.

推荐答案

我将使用相同的共享属性值创建第二个模型的全新实例,然后删除旧的实例.似乎对我来说是最干净的方式.

I would create an entirely new instance of the second model with the same values of their shared attributes, then delete the old one. Seems like the cleanest way to me.

如果ModelBase是抽象的:

If ModelBase is abstract:

instance = ModelA.objects.get(pk=1) #arbitrary        

# find parent class fields:
fields = [f.name for f in ModelBase._meta.fields]

# get the values from the modelA instance
values = dict( [(x, getattr(instance, x)) for x in fields] )

#assign same values to new instance of second model
new_instance = ModelB(**values) 

#add any additional information to new instance here

new_instance.save() #save new one
instance.delete() # remove the old one

但是,如果ModelBase不是 抽象,则您将不得不执行其他解决方法:

If ModelBase is not abstract, however, you'll have to do an extra workaround:

fields = [f.name for f in ModelBase._meta.fields if f.name != 'id']
#... other parts are the same...

new_instance.modelbase_ptr = instance.modelbase_ptr #re-assign related parent
instance.delete() #delete this first!
new_instance.save()

这篇关于将子类模型实例转换为Django中的另一个子类模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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