I try to update the PK in Django with the .save()
method, but when I save the object, Django duplicates the object with the same data but a different PK. For 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 PKs, and I want to change the PK without duplicating 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With