1

I know how to copy python object in to another as,

new_obj.__dict__ = original_obj.__dict__.copy()

But while playing with database, it overwrite the old object with new one.

I know the old_obj is overwritten because of same id.

So what I tried is , get latest id from database and add 1 to it as follows,

obj = Author.objects.latest('id')
put_id = obj.id + 1

And then use this put_id for saving another object.

Is this is right approach to save copied object to database or any other way to achieve this automatically ?

1

1 Answer 1

4

You just have to make the primary key None in order to get a new primary key for the new object

new_object = ModelName.objects.get(pk= #OLD_OBJECT_PK )
new_object.pk = None
new_object.save()
Sign up to request clarification or add additional context in comments.

Comments

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.