0

I need to change some objects primary keys in my django app, I wonder how can I achieve that?

Also my model has relations with other models.

1 Answer 1

2

Technically, it should be possible with an update query on the queryset:

MyModel.objects.filter(id=old_id).update(id=new_id)

The relations should cascade too if the constraints in the database have been set up correctly, but in general, I'd avoid updating PKs.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey man, when I use you method, I got the following error: IntegrityError: update or delete on table "restaurants_restaurant" violates foreign key constraint "restaurants_item_restaurant_id_32e74c18_fk_restauran" on table "restaurants_item" DETAIL: Key (id)=(101494) is still referenced from table "restaurants_item".
@VahidAl That's because your update is not cascading to foreign keys. You'd need to update either the tables depending on the key you're updating first or apply cascading constraints on the keys so that when you update the primary key it updates all of the dependent tables also.
Hey J Spratt, Thanks, I'm kindda new to django, can you explain a little more or do you new an implementation of it in codes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.