克隆继承的Django模型实例 [英] Clone an inherited django model instance
问题描述
当我克隆Django模型实例时,我曾经清理过 pk字段。
这似乎不适用于继承的模型:
When I clone a django model instance I used to clean the 'pk' field. This seems not to work with an inherited model :
执行以下操作:
class ModelA(models.Model):
info1 = models.CharField(max_length=64)
class ModelB(ModelA):
info2 = models.CharField(max_length=64)
class ModelC(ModelB):
info3 = models.CharField(max_length=64)
现在让我们创建一个实例并通过常规方式克隆它(我使用的是django shell):
Now let's create an instance and clone it by the 'usual' way ( I am using a django shell ):
In [1]: c=ModelC(info1="aaa",info2="bbb",info3="ccc")
In [2]: c.save()
In [3]: c.pk
Out[3]: 1L
In [4]: c.pk=None <------ to clone
In [5]: c.save() <------ should generate a new instance with a new index key
In [6]: c.pk
Out[6]: 1L <------ but don't
In [7]: ModelC.objects.all()
Out[7]: [<ModelC: ModelC object>] (only one instance !)
唯一的wa y我发现是这样做的:
The only way I found was to do :
In [16]: c.pk =None
In [17]: c.id=None
In [21]: c.modela_ptr_id=None
In [22]: c.modelb_ptr_id=None
In [23]: c.save()
In [24]: c.pk
Out[24]: 2L <---- successful clone containing info1,info2,info3 from original instance
In [25]: ModelC.objects.all()
Out[25]: [<ModelC: ModelC object>, <ModelC: ModelC object>]
我发现这很丑陋,有没有更好的方法可以从继承的对象中克隆实例模型?
I find that very ugly, is there a more nice way to clone an instance from an inherited model ?
推荐答案
c=ModelC(info1="aaa",info2="bbb",info3="ccc")
# creates an instance
c.save()
# writes instance to db
c.pk=None
# I doubt u can nullify the auto-generated pk of an existing object, because a pk is not nullable
c.save()
# if I'm right nothing will happen here.
所以c始终是同一对象。如果要克隆它,则需要生成一个新对象。在ModelC中使用构造函数:
So c will always be the same object. If you want to clone it you need to generate a new object. Either with a constructor within ModelC:
def __init__(another_modelC_obj=null, self):
if another_modelC_obj:
# for every field in another_modelC_obj: do self.field = another_modelC_obj.field
super().__init__()
所以你可以去
c2=ModelC(c)
或直接通过以下方式调用它:
Or call it directly with:
c2=ModelC(c.info1, c.info2, c.info3)
然后c2和c将尽管他们的pk是一样的
Then c2 and c will be identical despite of their pk
这篇关于克隆继承的Django模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!