Update primary key Django MySQL

家住魔仙堡 提交于 2019-12-01 17:00:27

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!