简体   繁体   中英

Update primary key Django MySQL

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 the 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 Docs

Django's Model.save() method relies on whether there's already a row with the same PK in your db to decide if it should issue an INSERT or UPDATE query.

As a more general rule: while it's technically possible to modify a PK at the SQL level, it's no necessarily such a good idea, as it means you'd have to update all related rows in all related tables (ok, still technically possible but really not a sane idea as far as I'm concerned), AND warn all applications depending on this PK of the change too - and then good luck. To make a long story short: it's always safer to consider PKs as immutable (and that's why quite a few people in the SQL world favor surrogate primary keys even when there's a seemingly obvious natural one).

First you should make sure that the object with the primary key "11111111L" has been added to your table. Probably doing something along the lines of:

e3 = Empleados.objects.get(pk="11111111L")

And then making sure that e3 contains . Once you confirm that it is there, then you can just use the following statement to get rid of the object with the primary key "56789034U" (assuming you keep e2 around):

e2.delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM