更新主键Django MySQL [英] Update primary key Django MySQL
问题描述
我尝试使用方法.save()更新Django中的PK,但是当我保存对象Django复制相同数据的对象但不同的PK,例如:
from gestion_empleados.Models import Empleados
>> ;> e = Empleados.objects.get(pk =56789034U)
>>> e.pk
u'56789034U'
>>> e.pk =11111111L
>>> e.save()
>>> e.pk
'11111111L'
>>> e2 = Empleados.objects.get(pk =56789034U)
>>> e2
< Empleados:Juan 56789034U>
>>> e
< Empleados:Juan 11111111L>
对象与不同的PK相同,我想要更改PK而不会重复对象。 / p>
任何解决方案?谢谢!
我不认为Django允许您更改对象的主键。您可能需要删除原始对象。
e2.delete()
根据Django文档
主键字段是只读的。如果您更改现有对象上主键的值,然后将其保存,则将创建一个新对象。
sorry for my poor english, my problem is:
I try to update the PK in Django with the method .save() but when i save the object Django duplicate the object withe the same data but differetn PK, example:
from gestion_empleados.Models import Empleados
>>> e = Empleados.objects.get(pk="56789034U")
>>> e.pk
u'56789034U'
>>> e.pk = "11111111L"
>>> e.save()
>>> e.pk
'11111111L'
>>> e2 = Empleados.objects.get(pk="56789034U")
>>> e2
<Empleados: Juan 56789034U>
>>> e
<Empleados: Juan 11111111L>
The objects are the same with different PK, and i want change the PK without duplicated the object.
Any solution? Thanks!
I don't think Django allows you to change the object's primary key. You may have to delete the original object.
e2.delete()
According to Django docs
The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.
这篇关于更新主键Django MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!