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 ?

Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • possible duplicate of [How do I clone a Django model instance object and save it to the database?](http://stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database) – rnevius Jun 01 '15 at 14:53

1 Answers1

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()
Othman
  • 2,942
  • 3
  • 22
  • 31