Update primary key Django MySQL Update primary key Django MySQL django django

Update primary key Django MySQL


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()